Python Exception Handling

Python Exception Handling

Exceptions:

Exceptions occur when the program encounters something unexpected, like trying to divide by zero or accessing an invalid index in a list. Python provides mechanisms to handle these exceptions and continue execution or terminate the program cleanly.

Exception Handling:

Exception Handling in Python is a way to handle runtime errors gracefully without crashing the program.

Syntax:

try:

# Code that may cause an exception
risky_operation()

Except ExceptionType:

# Code that runs if an exception occurs
handle_error()
#optional block

finally:

#Code that runs irrespective of exception occurring or not

Explanation:

    try: The block of code where the potential error might occur. Here, in this block, we have to place the code that we think might raise a problem or exception.
•    except: The block that handles the error if it occurs. Except block runs only if an exception occurs in out try block
•    finally: A block that runs no matter what. Finally block will run whether an exception occurs or not. This is an optional block.

Example 1:

Example without exception handling:

# Trying to divide by zero
result = 10 / 0
print(result)

Output

Explanation:

Example without exception handling:

try:
# Trying to divide by zero
result = 10 / 0
except ZeroDivisionError:
print(“Error: Cannot divide by zero!”)

Output

Explanation:

The code in the try block raises a ZeroDivisionError because dividing by zero is not allowed.
The except block catches the error and prints a message, preventing the program from crashing.

Example 2:

This example shows handling an IndexError when accessing an element that doesn’t exist.

Example without exception handling:

my_list = [10,20,30,40]
# Trying to access 5th element
my_list[4]

Output

Explanation:

There are 4 elements in the list with index 0-3 respectively. When we are trying to access the element at 4th index which doesn’t exist it is raising IndexError and crashing the program.

Example with exception handling:

try:
my_list = [10,20,30,40]
# Trying to access 5th element which is at index 4
my_list[4]
except IndexError:
print(“You are trying to access an index that doesn’t exist”)
finally:
print(“Finally block will run no matter what”)

Output

Explanation:

Here, as the exception occurred, except block executes and prints “You are trying to access an index that doesn’t exist” without crashing the program. And as finally blocks run even if exception occurs or not it will print “Finally block will run no matter what”

Below are some most commonly arising exceptions that can be handled same way as above:

Exception Example Explanation
ZeroDivisionError result = 10 / 0 Occurs when dividing a number by zero.
IndexError list1 = [1, 2, 3]; element = list1[5] Occurs when accessing an invalid index in a list or other indexable collections.
KeyError my_dict = {‘a’: 1}; value = my_dict[‘b’] Occurs when accessing a dictionary with a key that doesn’t exist.
TypeError result = ‘string’ + 5 Occurs when an operation or function is applied to an object of different types.
AttributeError my_list = [1, 2, 3]; my_list.add() Occurs when trying to access an attribute or method that doesn’t exist on an object.
NameError print(undef_var) Occurs when trying to access a variable or function that hasn’t been defined.
OverflowError number = math.exp(10**100) Occurs when a calculation exceeds the maximum limit for a number type.
SyntaxError eval(‘x === x’) Occurs when the code is not correctly written according to Python’s syntax rules.

Course Video

Course Video

YouTube Reference :

Frequently Asked Questions

Still have a question?

Let's talk

Python Exception Handling: Mechanism to handle runtime errors using try, except, else, and finally.

Types of Exceptions: Includes ZeroDivisionError, ValueError, FileNotFoundError, etc.

Exception Handling Used: To prevent program crashes by managing runtime errors.

Catch Exception in Python: Use try and except blocks.

Another Try in Except: It’s used for catching multiple exceptions or retrying the code.

Types of Exceptions: Built-in exceptions like IndexError, TypeError.

File Handling in Python: Reading, writing, and managing files.

Python File: Files used for input/output operations, handled by the open() function.

Number of Exceptions: Many built-in exceptions.

Try-Except in Python: Used to catch and handle errors during program execution.