Exception Handling in Python

Exception handling is the process of responding to unwanted or unexpected events (errors) during program execution.

If exceptions are not handled, the Python interpreter stops the program and displays an error message, which can crash the application.

Why Exception Handling is Important

Exceptions in Python

Python has many built-in exceptions that are raised when the program encounters an error.

When these exceptions occur, the Python interpreter stops the current process and passes it to the calling process until it is handled. If not handled, the program will crash.

try...except in Python

The try and except blocks are used in Python to handle errors and exceptions.

If the code inside the try block runs without error, the except block is skipped. If an error occurs, the except block executes.

Syntax

try:
    # Code that may raise an exception
except:
    # Code that runs if an exception occurs    

Example:

Python

try:
    num = int(input("Enter an integer: "))
except ValueError:
    print("Number entered is not an integer.")    

Output:

Output

Enter an integer: 6.022
Number entered is not an integer.    

A try clause can have multiple except clauses, but only one will be executed when an exception occurs.

Multiple except Blocks

A try block can have multiple except blocks to handle different exceptions.

Python

try:
    x = int(input("Enter a number: "))
    result = 10 / x
except ValueError:
    print("Invalid input! Please enter an integer.")
except ZeroDivisionError:
    print("Cannot divide by zero.")    

Key Points

Catching All Exceptions in Python

Sometimes you want to catch any unexpected error.

Basic Syntax

try:
    # Code that may fail
except Exception as e:
    print("Error:", e)    

Example:

Python

try:
    x = 1 / 0  # Division by zero
except Exception as e:
    print("Error:", e)    

Output:

Output

Error: division by zero    

Explanation