Python Tutorials
Basic

Data Structure and Data Types

String

List

Tuple

Set

Dictionary

Functions / Methods

Advance

Exception Handling

Python Exception Handling


Exception Handling

What is an Exception in Programming Languages?

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.


Difference Between Syntax Error and Exception

Syntax Error: The name suggests that this error results from incorrect syntax. It leads to the termination of the program.

Example
age = 18
if age >= 18
print("The person is eligible to vote.")
if age >= 18
            ^
SyntaxError: expected ':'

Here in the above example, we forgot the colon (:) after the if conditional statement, that's why we got the syntax error in the output.


Exceptions: Exceptions are raised when the program is syntactically correct, but the code results in an error. This error does not stop the execution of the program, however, it changes the normal flow of the program.

Example
number = 20
division = number / 0
print(division)
division = number / 0
ZeroDivisionError: division by zero

In the above example, we got a zero division error exception, because we are trying to divide a number by 0, in mathematics, we can not divide a number by 0.


Exception Handling in Python

The try and except statements are used to catch and handle exceptions in Python.

Statements that can raise exceptions are kept inside the try block, and the statements that handle the exception are written inside except blocks.

Example
try:
    number = 20
    division = number / 0
    print(division)
except:
    print("division by zero not allowed.")
division by zero not allowed.

Here, by using try and except block statements, we successfully handled the zero division error exception.


But, if there is no exception in the program, then the program runs smoothly and does not raise any exceptions.

Example
try:
    number = 20
    division = number / 10
    print(division)
except:
    print("division by zero not allowed.")
2.0

Now, we are dividing a number by 10, then in this case, there is no exception, so the program runs smoothly and prints the division number in the output.


Catching a Specific Exception

You can mention which exception you want to catch in the except block

Example
try:
    number = 20
    division = number / 0
    print(division)
except ZeroDivisionError:
    print("division by zero not allowed.")
division by zero not allowed.

Here in the above example, we mentioned the zero division error exception (ZeroDivisionError) class name in the except block.

When in the program, a zero division error exception occurs, then the except block will execute.


Display Exception Message

You can also display a Python return exception message like this.

Example
try:
    number = 20
    division = number / 0
    print(division)
except ZeroDivisionError as e:
    print("Exception:", e)
Exception: division by zero

Here, in the above example, we displayed the Python returned exception message for zero division error.


Multiple except Blocks

A try statement can have more than one except blocks, to specify handlers for different exceptions.

But note that at most only one except block is executed from the list.

Example
try:
    number = 20
    division = number / 2
    print("Result: " + division)
except ZeroDivisionError as e:
    print("Exception:", e)
except TypeError as e:
    print("Exception:", e)
Exception: can only concatenate str (not "float") to str

Here in the above example, we try to connect a string text with a number ("Result: " + division), but we can't directly connect a string text with a number data type in Python, so in this case a type error exception will occur.


What Happens When No except Blocks are Found From the List?

When no except block is found in the multiple except blocks list, then it raises an exception.

To avoid this, add a default except block at the end of the list.

You can not add a default except block at the beginning, because whenever an exception occurs, that default except block will be executed and it doesn't go to the next except blocks.

Example
try:
    number = 20
    division = number / 2
    print("Result:", division)

    numbers_list = [0, 1, 2, 3, 4, 5]
    print(numbers_list[10])

except ZeroDivisionError as e:
    print("Exception:", e)
except TypeError as e:
    print("Exception:", e)
except:
    print("Exception occured.")
Result: 10.0
Exception occured.

Here in the above example, there are no except block matches in the multiple exception list, in this case, it executed the default except block.


You can also add an Exception class name in the except block.

The Exception class is the base class for all the exceptions in Python.

Example
try:
    number = 20
    division = number / 2
    print("Result:", division)

    numbers_list = [0, 1, 2, 3, 4, 5]
    print(numbers_list[10])

except ZeroDivisionError as e:
    print("Exception:", e)
except TypeError as e:
    print("Exception:", e)
except Exception as e:
    print("Exception:", e)
Result: 10.0
Exception: list index out of range

Here, you can see the Exception class name is added with the default except block.


Try with Else Block

In Python, you can also use the else block on the try-except block, and it must be present after, all the except blocks.

The code enters the else block and executes only if the try block does not raise an exception.

Example
try:
    number = 20
    division = number / 2
    print(division)
except ZeroDivisionError as e:
    print("Exception:", e)
else:
    print("Else block")
10.0
Else block

Here in the above example, you can see that the program does not contain any exception, and it printed the number division and "Else block" text message.


Finally Keyword in Python

Python provides a keyword finally, which is always executed after the try and except blocks.

The finally block always executes after the normal termination of the try block, or after the try block terminates due to some exception.

Example
try:
    number = 20
    division = number / 2
    print(division)
except ZeroDivisionError as e:
    print("Exception:", e)
finally:
    print("Finally block")
10.0
Finally block

The above example does not have any exceptions, and it printed the number division and "Finally block" text message.


The finally block executes after the try block terminates due to some exceptions.

Example
try:
    number = 20
    division = number / 0
    print(division)
except ZeroDivisionError as e:
    print("Exception:", e)
finally:
    print("Finally block")
Exception: division by zero
Finally block

The above example raises a zero division error exception, so in the output, the zero division error exception message and "Finally block" message are printed.


Raise an Exception in Python

Python raise Keyword is used to raise exceptions or errors.

The raise keyword raises an error and stops the control flow of the program.

It is used to bring up the current exception in an exception handler so that it can be handled further up the call stack.

Example
number = 5
if number % 2 != 0:
    raise Exception("The number should not be an odd integer number.")
Exception: The number should not be an odd integer number.

Here in the above example, if the number is odd, we raised an exception.