Exception Handling in Python

Exception handling is an essential aspect of writing robust and reliable code in Python. It allows you to gracefully handle errors and unexpected situations that may arise during the execution of your program.

Try-Except Block:

        
            # Example of try-except block
            try:
                result = 10 / 0  # This will raise a ZeroDivisionError
            except ZeroDivisionError as e:
                print("Error:", e)
        
    

Handling Multiple Exceptions:

        
            # Example of handling multiple exceptions
            try:
                num = int(input("Enter a number: "))
                result = 10 / num
            except ZeroDivisionError as e:
                print("Error: Cannot divide by zero.")
            except ValueError as e:
                print("Error: Invalid input. Please enter a valid number.")
        
    

Finally Block:

        
            # Example of using the finally block
            try:
                # Code that might raise an exception
            except SomeException as e:
                # Exception handling
            finally:
                # Cleanup code, always executed
        
    

Custom Exceptions:

        
            # Example of a custom exception
            class CustomError(Exception):
                pass

            try:
                raise CustomError("This is a custom exception.")
            except CustomError as e:
                print("Custom Error:", e)
        
    

Exception Handling Exercise:

        
            # Exercise: Exception Handling for Division
            try:
                num1 = int(input("Enter the first number: "))
                num2 = int(input("Enter the second number: "))
                result = num1 / num2
                print("Result:", result)
            except ValueError:
                print("Error: Invalid input. Please enter valid numbers.")
            except ZeroDivisionError:
                print("Error: Cannot divide by zero.")
        
    

Exception handling is an important skill to ensure your code can gracefully recover from errors and prevent program crashes. Use exception handling to handle potential errors and maintain the reliability of your Python programs.

Using Try/Except Blocks for Error Handling YouTube Video