Python Exception Handling (original) (raw)

Last Updated : 02 Apr, 2025

Python Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let’s look at an example:

Handling a Simple Exception in Python

Exception handling helps in preventing crashes due to errors. Here’s a basic example demonstrating how to catch an exception and handle it gracefully:

Python `

Simple Exception Handling Example

n = 10 try: res = n / 0 # This will raise a ZeroDivisionError

except ZeroDivisionError: print("Can't be divided by zero!")

`

Output

Can't be divided by zero!

**Explanation: In this example, dividing number by 0 raises a **ZeroDivisionError. The try block contains the code that might cause an exception and the except block handles the exception, printing an error message instead of stopping the program.

Difference Between Exception and Error

**Example:

Python `

Syntax Error (Error)

print("Hello world" # Missing closing parenthesis

ZeroDivisionError (Exception)

n = 10 res = n / 0

`

**Explanation: A syntax error is a coding mistake that prevents the code from running. In contrast, an exception like ZeroDivisionError can be managed during the program’s execution using exception handling.

Syntax and Usage

Exception handling in Python is done using the try, except, else and finally blocks.

try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs

try, except, else and finally Blocks

**Example:

Python `

try: n = 0 res = 100 / n

except ZeroDivisionError: print("You can't divide by zero!")

except ValueError: print("Enter a valid number!")

else: print("Result is", res)

finally: print("Execution complete.")

`

Output

You can't divide by zero! Execution complete.

**Explanation:

Common Exceptions in Python

Python has many built-in exceptions, each representing a specific error condition. Some common ones include:

Exception Name Description
BaseException The base class for all built-in exceptions.
Exception The base class for all non-exit exceptions.
ArithmeticError Base class for all errors related to arithmetic operations.
ZeroDivisionError Raised when a division or modulo operation is performed with zero as the divisor.
OverflowError Raised when a numerical operation exceeds the maximum limit of a data type.
FloatingPointError Raised when a floating-point operation fails.
AssertionError Raised when an assert statement fails.
AttributeError Raised when an attribute reference or assignment fails.
IndexError Raised when a sequence subscript is out of range.
KeyError Raised when a dictionary key is not found.
MemoryError Raised when an operation runs out of memory.
NameError Raised when a local or global name is not found.
OSError Raised when a system-related operation (like file I/O) fails.
TypeError Raised when an operation or function is applied to an object of inappropriate type.
ValueError Raised when a function receives an argument of the right type but inappropriate value.
ImportError Raised when an import statement has issues.
ModuleNotFoundError Raised when a module cannot be found.

Python Catching Exceptions

When working with exceptions in Python, we can handle errors more efficiently by specifying the types of exceptions we expect. This can make code both safer and easier to debug.

Catching Specific Exceptions

Catching specific exceptions makes code to respond to different exception types differently.

**Example:

Python `

try: x = int("str") # This will cause ValueError

#inverse
inv = 1 / x

except ValueError: print("Not Valid!")

except ZeroDivisionError: print("Zero has no inverse!")

`

**Explanation:

Catching Multiple Exceptions

We can catch multiple exceptions in a single block if we need to handle them in the same way or we can separate them if different types of exceptions require different handling.

**Example:

Python `

a = ["10", "twenty", 30] # Mixed list of integers and strings try: total = int(a[0]) + int(a[1]) # 'twenty' cannot be converted to int

except (ValueError, TypeError) as e: print("Error", e)

except IndexError: print("Index out of range.")

`

Output

Error invalid literal for int() with base 10: 'twenty'

**Explanation:

Catch-All Handlers and Their Risks

Here’s a simple calculation that may fail due to various reasons.

**Example:

Python `

try: # Simulate risky calculation: incorrect type operation res = "100" / 20

except ArithmeticError: print("Arithmetic problem.")

except: print("Something went wrong!")

`

Output

Something went wrong!

**Explanation:

Raise an Exception

We raise an exception in Python using the raise keyword followed by an instance of the exception class that we want to trigger. We can choose from built-in exceptions or define our own custom exceptions by inheriting from Python’s built-in Exception class.

**Basic Syntax:

raise ExceptionType(“Error message”)

**Example:

Python `

def set(age): if age < 0: raise ValueError("Age cannot be negative.") print(f"Age set to {age}")

try: set(-5) except ValueError as e: print(e)

`

Output

Age cannot be negative.

**Explanation:

Advantages of Exception Handling:

Disadvantages of Exception Handling: