Exception Handling in Python
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Exception Handling in Python

Kishore V


Exception Handling in Python

In Python, exception handling allows you to manage runtime errors gracefully instead of letting the program crash.

This is done using the try, except, else, and finally blocks.

Understanding the Exception Blocks

  • try → Tests a block of code for possible errors
  • except → Handles the error if one occurs
  • else → Executes when no error occurs
  • finally → Executes no matter what (error or no error)

Basic Exception Handling

When an error occurs, Python normally stops execution and shows an error message.

Using try and except, you can catch and handle that error.

Example: Handling an Undefined Variable

An error occurred: variable is not defined

Handling Multiple Exceptions

You can use multiple except blocks to handle different types of errors differently.

Example: Specific vs General Errors

Conversion failed: not a valid number

Using the else Block

The else block runs only if no exception occurs in the try block.

Example: Successful Execution

Division successful: 5.0

Using the finally Block

The finally block always executes, whether an exception occurs or not. It is ideal for cleanup tasks.

Example: Finally Block Execution

Execution completed

Raising Exceptions Manually

You can force an exception to occur using the raise keyword.

Example: Raise ValueError

Traceback (most recent call last): File "main.py", line 3, in <module> raise ValueError("Age cannot be negative") ValueError: Age cannot be negative

Our website uses cookies to enhance your experience. Learn More
Accept !