Exception Handling in Python: Complete Guide | FACE Prep

Exception Handling in Python: Complete Guide | FACE Prep

Exception Handling in Python

In Python programming, exception handling is a fundamental concept that ensures your program can handle unexpected errors during runtime without crashing. By gracefully managing exceptions, Python allows your program to continue executing smoothly even when things go wrong. In this guide, we will explore what exceptions are, why exception handling is necessary, and how to use the different exception handling mechanisms in Python.

What is an Exception in Python?

Exception Handling in PythonAn exception is a runtime error that disrupts the normal flow of a program. When an exception occurs, the program stops executing and displays an error message. For example, if your code tries to divide a number by zero, Python will throw a ZeroDivisionError exception.

Example: Division by Zero

python
# Program to divide two numbers a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) res = a / b print(int(res)) print("FACE Prep")
If you input 10 and 0, the program will raise the following exception:
vbnet
Traceback (most recent call last): File "main.py", line 3, in <module> res = a / b ZeroDivisionError: division by zero

Why Do Exceptions Occur?

Exceptions occur due to a variety of reasons, such as:
  • Trying to open a non-existent file (FileNotFoundError)
  • Dividing by zero (ZeroDivisionError)
  • Importing a module that doesn’t exist (ImportError)

Common Python Exceptions

Here are some common exceptions that you might encounter when working with Python:
  • ZeroDivisionError: Occurs when a number is divided by zero.
  • FileNotFoundError: Raised when trying to access a file that doesn’t exist.
  • ImportError: Triggered when a module cannot be found.
  • NameError: Raised when a local or global variable is not found.
  • IOError: Happens when input/output operations fail.
  • EOFError: Occurs when the end of a file is reached unexpectedly.
By handling exceptions effectively, you can prevent your program from crashing unexpectedly and provide more user-friendly feedback.

Why is Exception Handling Important?

Without exception handling, your program will terminate abruptly when an error occurs, potentially causing loss of data or an incomplete user experience. Exception handling allows you to catch and manage these errors gracefully, ensuring that the program continues to execute, even if one part fails.

Benefits of Exception Handling:

  • Prevents Program Crashes: By catching errors, your program can continue executing even when an issue arises.
  • Improves User Experience: Inform users about errors with helpful messages instead of crashing the application.
  • Maintains Program Integrity: Safeguard important operations, such as saving data or closing files, even after an error occurs.

Python Exception Handling Blocks

Python provides four blocks for exception handling: try, except, else, and finally. Let’s explore each one in detail.

1. try and except

The try block contains the code that may raise an exception. The except block contains the code to handle the exception if one occurs.

Example: Handling Division by Zero

python
try: a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) res = a / b except ZeroDivisionError: print("Cannot divide by zero")
If the user inputs 10 and 0, the ZeroDivisionError will be caught, and the message “Cannot divide by zero” will be printed. 

2. else Block

The else block contains the code that runs when no exceptions occur. It is optional and is typically used when you want to execute certain actions only when the code in the try block is error-free.

Example: Using else for Successful Division

python
try: a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) res = a / b except ZeroDivisionError: print("Cannot divide by zero") else: print(f"The result is: {int(res)}") print("FACE Prep")
If no error occurs (e.g., the user inputs 10 and 5), the else block will execute and print the result.

Click Here to Know more our program!Exception Handling in Python