Exception Handling in Python: Detailed Explanation

 

Exception Handling in Python: Detailed Explanation


1. What are Exceptions?

An exception is an error that occurs during program execution. When a Python program encounters an error, it terminates the normal flow of the program and raises an exception.

For example:

print(5 / 0)  # Division by zero

Output:

ZeroDivisionError: division by zero

Here, ZeroDivisionError is an exception.


2. Built-in Exceptions

Python provides several built-in exceptions that can be raised when errors occur. Here are some common ones:

Exception Description
ZeroDivisionError Raised when dividing a number by zero.
ValueError Raised when an invalid value is passed.
TypeError Raised when an operation is performed on incompatible types.
IndexError Raised when trying to access an invalid list index.
KeyError Raised when trying to access a non-existent key in a dictionary.
NameError Raised when a variable or function is not defined.
AttributeError Raised when an invalid attribute is accessed.
FileNotFoundError Raised when a file or directory is not found.
ImportError Raised when an imported module is not found.
SyntaxError Raised when there is an error in Python syntax.
IndentationError Raised when there is an incorrect indentation.

3. Exception Handling

To handle exceptions gracefully and avoid program crashes, Python uses a try-except block.

Syntax:

try:
    # Code that may raise an exception
except ExceptionType:
    # Code to handle the exception
else:
    # Code that executes if no exception occurs (optional)
finally:
    # Code that always executes (optional)

3.1 Basic Try-Except Block

The try block contains the code that might raise an exception. If an exception occurs, it jumps to the except block.

Example:

try:
    result = 5 / 0  # This will raise ZeroDivisionError
except ZeroDivisionError:
    print("Cannot divide by zero!")

Output:

Cannot divide by zero!

3.2 Handling Multiple Exceptions

You can handle multiple exceptions using multiple except blocks.

Example:

try:
    num = int("abc")  # This will raise ValueError
    result = 10 / 0   # This will raise ZeroDivisionError
except ValueError:
    print("Invalid value provided!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

Output:

Invalid value provided!

3.3 Catching All Exceptions

To handle any exception, use a generic except block.

Example:

try:
    print(10 / 0)
except Exception as e:
    print(f"An error occurred: {e}")

Output:

An error occurred: division by zero

3.4 Else Block

The else block executes if no exception occurs in the try block.

Example:

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print("Division successful:", result)

Output:

Division successful: 5.0

3.5 Finally Block

The finally block executes regardless of whether an exception occurs.

Example:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("Execution finished.")

Output:

Cannot divide by zero!
Execution finished.

4. Raising Exceptions

You can manually raise an exception using the raise keyword.

Syntax:

raise ExceptionType("Error message")

Example:

def check_age(age):
    if age < 18:
        raise ValueError("Age must be 18 or above.")
    print("Age is valid!")

try:
    check_age(16)
except ValueError as e:
    print(f"Error: {e}")

Output:

Error: Age must be 18 or above.

5. User-Defined Exceptions

Python allows you to create custom exceptions by defining a new class that inherits from the built-in Exception class.

Example:

# Define a custom exception
class AgeTooLowError(Exception):
    def __init__(self, age, message="Age must be at least 18."):
        self.age = age
        self.message = message
        super().__init__(self.message)

# Function that raises the custom exception
def check_age(age):
    if age < 18:
        raise AgeTooLowError(age)
    print("Age is valid!")

# Handling the custom exception
try:
    check_age(15)
except AgeTooLowError as e:
    print(f"Custom Exception: {e}")

Output:

Custom Exception: Age must be at least 18.

6. Summary Table

Feature Description
Exception An error during program execution that interrupts the flow.
Built-in Exceptions Predefined exceptions like ValueError, TypeError, etc.
try-except Block Used to handle exceptions and prevent program crashes.
Multiple Exceptions Use multiple except blocks to handle specific exceptions.
Else Block Executes if no exception occurs.
Finally Block Executes regardless of whether an exception occurs.
raise Used to manually raise exceptions.
Custom Exceptions Define user-defined exceptions by inheriting from Exception.

7. Key Points to Remember

  1. Use try to enclose code that might raise exceptions.
  2. Handle exceptions with except.
  3. Use finally for cleanup actions (e.g., closing files or releasing resources).
  4. Use raise to trigger exceptions intentionally.
  5. You can create custom exceptions for specific error-handling scenarios.

Let me know if you'd like further clarification or more examples! 😊

Comments

Popular posts from this blog

Keyword , Identifier, Indentation, Comments & Documentation

DSA Lab 8 program

DSA Lab 7 Program