Exception Handling

Learn how to handle errors in Python using try-except, finally, raise, and custom exceptions with simple examples.

Loading...
Exception Handling

Exception handling means dealing with unexpected errors in a program.

It helps the program keep running smoothly instead of crashing when something goes wrong.

What are Exceptions?

An exception is an error that occurs during program execution.

Python has several built-in exceptions to handle errors like invalid input, type mismatches, or index out of bounds.

If an exception is not handled, the program terminates with a traceback.

Exception handling prevents this by providing alternative code execution paths.

Using try...except

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

The code in try block runs when there is no error. If an error occurs in the try block, the except block is executed.

Syntax:

try:
    # Code that may raise an exception
except:
    # Code to handle the exception

Example:

a = input("Enter a number: ")
print(f"Multiplication table of {a}:")
 
try:
    for i in range(1, 11):
        print(f"{int(a)} x {i} = {int(a) * i}")
except:
    print("Invalid input!")
 
print("End of program.")

Output (Valid Input):

Enter a number: 5
Multiplication table of 5: 
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
End of program.

Output (Invalid Input):

Enter a number: 3.2
Multiplication table of 3.2: 
Invalid  Input!
End of program.

Handling Multiple Exceptions

You can handle specific exceptions separately by using multiple except blocks.

try:
    num = int(input("Enter an integer: "))
    a = [6, 3]
    print(a[num])
except ValueError:
    print("The input is not an integer.")
except IndexError:
    print("Index is out of range.")

The finally Clause

The finally block is executed no matter what. Whether an exception is raised or not. It is often used for cleanup tasks like closing files or releasing resources.

Syntax:

try:
    # Code that may raise an exception
except:
    # Code to handle exceptions
finally:
    # Code that always executes

Example:

try:
    num = int(input("Enter an integer: "))
except ValueError:
    print("Invalid input.")
else:
    print("Input accepted.")
finally:
    print("This block always executes.")

Output (Valid Input):

Enter an integer: 10
Input accepted.
This block always executes.

Output (Invalid Input):

Enter an integer: abc
Invalid input.
This block always executes.

Raising Exceptions

You can explicitly raise exceptions by using the raise keyword. This is useful for enforcing specific conditions in your code.

For example:

value = int(input("Enter a value between 5 and 9: "))
 
if value < 5 or value > 9:
    raise ValueError("Value must be between 5 and 9.")
else:
    print("Valid input!")

Output (Valid Input):

Enter a value between 5 and 9: 7
Valid input!

Output (Invalid Input):

Enter a value between 5 and 9: 3
ValueError: Value must be between 5 and 9.

Custom Exceptions

You can define custom exceptions by creating a class that inherits from Python’s built-in Exception class.

This is useful when handling application-specific errors.

Defining a Custom Exception:

class CustomError(Exception):
    pass
 
try:
    raise CustomError("This is a custom exception.")
except CustomError as e:
    print(e)

👉 Next tutorial: Python Enumerate Function

Support my work!