Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 6 - Exception Handling

6.2 Handling Exceptions

Exception handling in Python is managed using the try-except block, where:

  • The try block encloses the code that might raise an exception.
  • The except block handles specific exceptions that occur within the try block.

For example, if you attempt to divide 10 by 0, it will raise a ZeroDivisionError. You can handle this error using a try-except block as shown:

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

In this example:

  • The try block attempts to perform the division 10 / 0, which raises a ZeroDivisionError.
  • The except block catches the ZeroDivisionError and prints a message "Cannot divide by zero!".

Now, you can modify the divisor (0) to any other number (e.g., 2, 5, 10) and observe how the program executes without raising a ZeroDivisionError. For instance:

try:
    result = 10 / 5
    print(result)
except ZeroDivisionError:
    print("Cannot divide by zero!")

In this case, the division operation 10 / 5 will successfully execute, and result will be 2.0, which will be printed to the console.