How to handle exceptions : example of ZeroDivisionError exception

Lesson Details:
June 29, 2020


I: Introduction

A: Python is an interpreted, general-purpose, high-level programming language that has been around for 25 years (since 1991).

B: It’s used for web applications, games, desktop apps, data science, and much more.

C: It’s used in the tech industry for its simplicity and to get things done quickly.

D: It’s also easy to learn, unlike other languages like Java or C++.

II: Body

A: How to handle exceptions : example of zerodivisionerror exception

B: Exceptions are errors or events that cause a program to terminate abnormally when they occur.

C: Exceptions are usually caused by invalid input when working with functions.

D: An exception can be either caught or uncaught, depending on whether the programmer wants to control what happens when it occurs.

E: When you catch an exception, you can show a dialog box, print an error message, or call a function to handle the error condition.

F: To handle an exception, you must use the try…catch statement. Within the try block, you will place all code that may potentially throw an exception. The following shows an example of catching an exception in Python.

try: print("Please enter an integer") x = int(input("")) except ZeroDivisionError as zde: print("It appears that you are trying to divide by zero.") print("Here are some examples of legal division:" ) print("5 / 2 = 2.5") print("9 / 4 = 2.25") print("10 / 0 = Infinity") print("0 / 0 = NaN") print("") print("Here are some examples of illegal division:" ) print("4 / 5 = 0") print("9 / 0 = inf") print("0 / 0 = inf") print("") else: print(zde) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 try : print ( "Please enter an integer" ) x = int ( input ( "" ) ) except ZeroDivisionError as zde : print ( "It appears that you are trying to divide by zero." ) print ( "Here are some examples of legal division:" ) print ( "5 / 2 = 2.5" ) print ( "9 / 4 = 2.25" ) print ( "10 / 0 = Infinity" ) print ( "0 / 0 = NaN" ) print ( "" ) print ( "Here are some examples of illegal division:" ) print ( "4 / 5 = 0" ) print ( "9 / 0 = inf" ) print ( "0 / 0 = inf" ) print ( "" ) else : print ( zde )

III: Conclusion

loader
Course content