Lecture # 10 - Error Handling with Try-Except

Try/Except:

In Python, the try and except blocks are used for exception handling, allowing you to gracefully handle errors or exceptions that occur during program execution.

try Block: The try block lets you test a block of code for errors.

except Block: The except block catches the error and lets you handle it.

Syntax:

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

Here's how it works:

  1. The code inside the try block is executed.

  2. If an exception occurs within the try block, the execution is immediately interrupted, and the control is transferred to the except block.

  3. If the exception matches the specified ExceptionType (or its subclass), the code inside the corresponding except block is executed to handle the exception.

  4. If the exception does not match any of the specified ExceptionType, it is propagated up the call stack, and if not caught anywhere else, the program terminates with an error message.

You can also use multiple except blocks to handle different types of exceptions:

try:
    # Code that may raise an exception
except TypeError:
    # Code to handle TypeError
except ValueError:
    # Code to handle ValueError
except Exception:
    # Code to handle any other type of exception

You can also use except block without specifying the type of exception to catch all exceptions:

try:
    # Code that may raise an exception
except:
    # Code to handle any type of exception

Example 1:

try:
    x = int(input("Please enter a number: "))
    result = 10 / x
    print("Result:", result)
except ValueError:
    print("Invalid input! Please enter a valid number.")

Output:

Example 2:

try:
    number = int(input("Please enter a number: "))
    result = 10 / number
    print("Result:", result)
except ZeroDivisionError:
    # Handling the specific exception (division by zero)
    print("Division by zero is not allowed.")
except ValueError:
    # Handling the specific exception (invalid input)
    print("Invalid input! Please enter a valid number.")
except Exception as e:
    # Handling any other unexpected exceptions
    print("An unexpected error occurred:", e)

Output:

Example 3:

try:
    number = int(input("Please enter a number: "))
    result = 10 / number
    print("Result:", result)
except:
    print("An error occurred. Please check your input.")

Output:

0
Subscribe to my newsletter

Read articles from Abdullah Bin Altaf directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Abdullah Bin Altaf
Abdullah Bin Altaf