Python Try Except – Exception Handling in Python

Exception Handling in Python Using Try and Except Statements

In this tutorial, you'll learn what exceptions are and how to handle exceptions in your Python programs using try and except statements. 

In Python, the exception handling allows you to prevent the programs from crashing when something goes wrong during execution.

What are Exceptions in Python?

Python terminates and generates an error message as soon as an error occurs. In Python, an error can be syntax error or exception.

Syntax Error

Let's take a look at an example of a syntax error:

print("This is an syntax error!"))

Output:

Python generates an error message as follows:

SyntaxError: invalid syntax

This error occurred because there are two close parentheses for the print() function.

Exceptions

Let's take a look at an example of how an exception occurs in the Python program:

value = 10 / 0

Output:

Python generates an error message as follows:

ZeroDivisionError: division by zero

This error occurred because number 10 divides by 0 is undefined.

Let's take a look at another example:

name = 100 + '40'

Output:

Python generates an error message as follows:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

This error occurred because we're trying to add 100 to the string '40'.

The number 100 and the string '40' are different types.

Exception Handling in Python

To handle exceptions in Python, you use the try statement.
The syntax of a try statement is as follows:

try:
#do something
except:
#handle an exception

The try statement works as follows:

  • First, Python executes the code inside the try clause.
  • If no exception occurs, Python skips the exception clause and finishes the execution of the try statement.
  • If an exception occurs during the execution of the try clause, Python skips the rest of the code in the try clause.
  • If an exception occurs and does not match an exception in the except clause, Python passes it on the outer try statement. 

try statement may have more than one except clause to specify multiple handlers for different exceptions. However, at most, one exception handler will be executed.

try:
#do something
except(exception1 [, exception2, …]):
#handle multiple exceptions
except:
#handle all other exceptions

Exception Handling Examples

The following code illustrates an example of the ZeroDivisionError exception handling:

try:
x = 10 / 0
except ZeroDivisionError:
print("The ZeroDivisionError exception occurs!")
except:
print("The other exception occurs!")

Output:

The ZeroDivisionError exception occurs!

Since 10/0 is the ZeroDivisionError exception, the exception has occurred, Python passes it on to the ZeroDivisionError exception clause.

Let's take a look at another example:

try:
name = 100 + '40'
except ZeroDivisionError:
print("The ZeroDivisionError exception occurs!")
except:
print("The other exception occurs!")

Output:

The other exception occurs!

Since the exception has occurred and does not match the ZeroDivisionError exception clause, Python passes it on to the except clause.

Here is another example illustrates how to specify handlers for difference exceptions:

try:
name = 100 + '40'
except ZeroDivisionError:
print("The ZeroDivisionError exception occurs!")
except TypeError:
print("The TypeError exception occurs!")
except:
print("The other exception occurs!")

You also can specify more than one exception in the exception clause, as shown in the following example:

try:
name = 100 + '40'
except (ZeroDivisionError, TypeError):
print("The TypeError or ZeroDivisionError exception occurs!")
except:
print("The other exception occurs!")

Raising Exceptions

You can use the raise statement to throw an exception if an error occurs.

The following illustrates an example of using the raise statement to force the ZeroDivisionError exception to occur:

try:
raise ZeroDivisionError
except ZeroDivisionError:
print("The ZeroDivisionError exception occurs!")

Try and Finally

You can use the Python finally clause along with the try statement. The Python finally clause is optional and always executed before leaving the try statement, whether an exception has occurred or not.

Here is an example:

try:
file_exist = True
file = open("employee_list.txt", 'r') #open the employee_list.txt file.
x = 10 / 0 #this causes an error.
except FileNotFoundError:
print ("The file is not found!")
file_exist = False
finally:
if file_exist:
print("Close the file")
file.close() #close the file.

Output:

If the file employee_list.txt exists, you'll get the output like this:

Close the file
Traceback (most recent call last):
File "exception.py", line 4, in
x = 10 / 0 #this causes an error.
ZeroDivisionError: division by zero

And if the file doesn't exist, you'll get the output like this:

The file is not found!

In this tutorial, you've learned what exceptions are, and how to handle exceptions in Python programs using the try and except statements. 

In Python, you can use the raise statement to force a specified exception to occur, and you can also use the Python finally clause along with the try statement, which is optional, and always executed before leaving the try statement whether an exception has occurred or not. With exception handling, you can prevent your programs from crashing when something goes wrong.


See also:
Python return Statement with Examples
Python List Methods and Functions with Examples
Python abs() – Absolute Value in Python
Python Factorial – Find the Factorial of a Number
Python min() – Find the Smallest Value in Python

Leave a Comment