Unit– III Exception handling

Sagar SangamSagar Sangam
5 min read

Introduction to Exception

Exception Handling handles errors that occur during the execution of a program. Exception handling allows one 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.

Example: Trying to divide a number by zero will cause an exception.

# Example of an exception

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

  • Error: Errors are serious issues that a program should not try to handle. They are usually problems in the code’s logic or configuration and need to be fixed by the programmer. Examples include syntax errors and memory errors.

  • Exception: Exceptions are less severe than errors and can be handled by the program. They occur due to situations like invalid input, missing files or network issues.

Example:

1

# Syntax Error (Error)

2

print("Hello world" # Missing closing parenthesis

3

4

# ZeroDivisionError (Exception)

5

n = 10

6

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.

Types of Exceptions in Python

Python exceptions are categorized into two main types:

  1. Built-in Exceptions

  2. User-defined Exceptions

1. Built-in Exceptions

Built-in exceptions are predefined errors that occur during program execution.

Example: Handling ZeroDivisionError (Built-in Exception)

python

try:

x = 10 / 0 # Division by zero

except ZeroDivisionError as e:

print("Error:", e) # Handling the exception

Explanation

The try block contains 10/0, which raises a ZeroDivisionError.

The except block catches this error and prints a custom message.

Syntax of Exception Handling:

python

try:

Code that may raise an exception

except ExceptionType:

Code to handle the exception

finally:

Optional cleanup code (always executes)

2. User-defined Exceptions

These are custom exceptions created by the programmer using class inheritance.

Example: Creating and Handling a User-defined Exception

python

CopyEdit

class CustomError(Exception): # Inheriting from Exception class

def init(self, message):

super().__init__(message)

try:

raise CustomError("This is a custom exception!") # Raising custom exception

except CustomError as e:

print("Caught Exception:", e)

Explanation:

A custom exception CustomError is created by inheriting from the Exception class.

raise CustomError("This is a custom exception!") generates an error manually.

The except block catches this exception and prints the error message

Raising 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:

1

def set(age):

2

if age < 0:

3

raise ValueError("Age cannot be negative.")

4

print(f"Age set to {age}")

5

try:

7

set(-5)

8

except ValueError as e:

9

print(e)

Output

Age cannot be negative.

Explanation:

  • The function set checks if the age is negative. If so, it raises a ValueError with a message explaining the issue.

  • This ensures that the age attribute cannot be set to an invalid state, thus maintaining the integrity of the data.

Handling Exception

Exception handling in Python is a mechanism that allows a program to detect, handle, and recover from runtime errors (exceptions) without crashing. It ensures that even if an error occurs, the program can respond gracefully instead of abruptly stopping execution.

try, except, else and finally Blocks

  • try Block: try Block lets us test a block of code for errors. Python will “try” to execute the code in this block. If an exception occurs, execution will immediately jump to the except block.

  • except Block: except Block enables us to handle the error or exception. If the code inside the try block throws an error, Python jumps to the except block and executes it. We can handle specific exceptions or use a general except to catch all exceptions.

  • else Block: else Block is optional and if included, must follow all except blocks. The else block runs only if no exceptions are raised in the try block. This is useful for code that should execute if the try block succeeds.

  • finally Block: finally Block always runs, regardless of whether an exception occurred or not. It is typically used for cleanup operations (closing files, releasing resources).

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

Example:

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:

  • try block asks for user input and tries to divide 100 by the input number.

  • except blocks handle ZeroDivisionError and ValueError.

  • else block runs if no exception occurs, displaying the result.

  • finally block runs regardless of the outcome, indicating the completion of execution.

0
Subscribe to my newsletter

Read articles from Sagar Sangam directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sagar Sangam
Sagar Sangam