Python Exception Handling

In Python, exceptions are handled using try, except, else, and finally blocks, which allow you to catch errors gracefully instead of crashing the program. This mechanism is essential for building robust applications that can deal with unexpected inputs, missing files, or runtime errors. Let’s break it down with clear examples.

Key Concepts of Exception Handling

  • Exception: An error that occurs during program execution (e.g., division by zero, invalid input).
  • try block: Code that may raise an exception.
  • except block: Code that runs if an exception occurs.
  • else block: Code that runs if no exception occurs.
  • finally block: Code that always runs, whether an exception occurs or not.
  • raise keyword: Used to manually throw exceptions.

Basic Example

Let us see an example to handle exceptions in Python:

try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print("Result:", result)
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
except ValueError:
    print("Error: Invalid input, please enter a number.")

Output

Enter a number: Error: Cannot divide by zero!

Using else and finally

In this example, we will use the following to handle exceptions:

  • else runs only if no exception occurs.
  • finally runs regardless (useful for closing files, releasing resources).

Here is the example:

try:
    num = 5
    result = 10 / num
except ZeroDivisionError:
    print("Division by zero error!")
else:
    print("Division successful:", result)
finally:
    print("Execution completed.")

Output

Division successful: 2.0
Execution completed.

Raising Exceptions

In this example, ValueError will be raised if the condition fails:

def check_age(age):
    if age < 18:
        raise ValueError("For voting, age should be 18 or above.")
    else:
        print("Can Vote")

check_age(10)

Output

raise ValueError("For voting, age should be 18 or above.")
ValueError: For voting, age should be 18 or above.

Comparison Table

Python Exception Handling

 


If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

Python Regular Expressions
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment