Exception Handling in Python

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

Output:

An error occurred: variable is not defined
Try it Yourself

Since total is not defined, the except block runs instead of crashing the program.

Program Without Exception Handling

Without try-except, the program stops immediately when an error occurs.

Example:

Output:

NameError: name 'total' is not defined
Try it Yourself

This will raise a runtime error and stop execution.

Handling Multiple Exceptions

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

Example: Specific vs General Errors

Output:

Conversion failed: not a valid number
Try it Yourself

This allows you to provide more meaningful error messages.

Using the else Block

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

Example: Successful Execution

Output:

Division successful: 5.0
Try it Yourself

Using the finally Block

The finally block always executes, whether an exception occurs or not.

It is commonly used for cleanup tasks like closing files or releasing resources.

Example: Finally Block Execution

Output:

Execution completed
Try it Yourself

Real-World Example: File Handling with Exceptions

The finally block ensures that a file is closed properly.

Output:

File not found
Try it Yourself

This prevents resource leaks even if an error occurs.

Raising Exceptions Manually

As a developer, you can raise your own exceptions when certain conditions are met using the raise keyword.

Example: Raise an Exception for Invalid Values

Output:

Exception: Score cannot be negative
Try it Yourself

Raising Specific Exception Types

You can raise built-in exception types like TypeError, ValueError, etc.

Example: Raise TypeError

Output:

TypeError: Age must be an integer
Try it Yourself

Why Use Exception Handling?

  • Prevents program crashes
  • Improves user experience
  • Makes debugging easier
  • Ensures clean resource management

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