Python Error Handling

Try and Except

In Python, errors and exceptions can disrupt the flow of your program. To handle these issues gracefully, Python provides try and except blocks, which allow you to catch and manage exceptions without crashing your program.

Syntax

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

Example

try:
    result = 10 / 0
except ZeroDivisionError:
    print("You can't divide by zero!")
  • The code inside the try block is executed first.
  • If an exception occurs, the code inside the except block is executed, handling the error.

Finally

The finally block is used to define cleanup actions that should be executed under all circumstances, whether an exception occurred or not.

Syntax

try:
    # Code that may raise an exception
except SomeException:
    # Code to handle the exception
finally:
    # Code that will always execute

Example

try:
    file = open("example.txt", "r")
except FileNotFoundError:
    print("File not found!")
finally:
    print("Execution complete.")
  • The finally block runs regardless of whether an exception was raised or not, making it useful for resource cleanup like closing files.

Raising Exceptions

You can raise exceptions in your code using the raise keyword. This is useful when you want to trigger an exception manually.

Syntax

if condition:
    raise SomeException("Error message")

Example

age = -1
if age < 0:
    raise ValueError("Age cannot be negative!")
  • The raise statement is used to throw a specified exception with an optional error message.

Handling Multiple Exceptions

You can handle multiple exceptions by specifying them as a tuple in the except block or by chaining multiple except blocks.

Syntax

try:
    # Code that may raise exceptions
except (ExceptionType1, ExceptionType2):
    # Code to handle the exceptions

Example

try:
    result = 10 / 0
except (ZeroDivisionError, TypeError):
    print("An error occurred!")
  • You can catch multiple types of exceptions using a single except block or handle each exception type in separate blocks.

Scroll to Top