Python Exception Handling

In Python, exceptions are handled using try, except, else, finally, and raise 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 to handle exceptions

Let us see an example to handle exceptions in Python with try and except:

# Handle exceptions in Python with try and except
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 to handle exceptions

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:

# Using else and finally to handle exceptions in Python
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.

Let us understand the flow of execution of the above program:

  • num = 5
  • result = 10 / 5 = 2.0 → No exception occurs.
  • Since no error is raised, the except block is skipped.
  • The else block runs → prints:
    Division successful: 2.0
  • The finally block always runs → prints:
    Execution completed.

Raising Exceptions with the raise keyword

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

# Raising exceptions in Python with the raise keyword

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

try:
  check_age(10)
except ValueError as e:
    print("Value Error = ", e)

Output

Value Error =  For voting, age should be 18 or above.

Let us understand the flow of execution of the above program:

  • Function Call
    • check_age(10) is invoked.
  • Enter Function
    • Execution jumps inside check_age(age) with age = 10.
  • Condition Check
    • if age < 18 → evaluates to True (since 10 < 18).
  • Raise Exception
    • raise ValueError("For voting, age should be 18 or above.") is executed.
    • Normal flow stops here, and Python throws a ValueError.
  • Exception Handling
    • If wrapped in a try-except block:
      • Control jumps to the except ValueError as e: block.
      • Prints: "Value Error = For voting, age should be 18 or above."
  • Continue Execution
    • Program continues with the next iteration (if in a loop) or the next statement after the try-except.

Comparison Table

Python Exception Handling

Video Tutorial – Exception Handling in Python (English)

Video Tutorial – Exception Handling in Python (Hindi)

 


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