0% found this document useful (0 votes)
12 views

Error and Exception Handling

Error and exception handling in Python is essential for developing reliable programs by managing unexpected situations without crashing. It involves understanding different types of errors, such as syntax errors and runtime errors, and using try, except, else, and finally blocks to handle exceptions. Additionally, Python allows catching multiple exceptions and raising custom exceptions to enhance error management.

Uploaded by

Akshat Joshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Error and Exception Handling

Error and exception handling in Python is essential for developing reliable programs by managing unexpected situations without crashing. It involves understanding different types of errors, such as syntax errors and runtime errors, and using try, except, else, and finally blocks to handle exceptions. Additionally, Python allows catching multiple exceptions and raising custom exceptions to enhance error management.

Uploaded by

Akshat Joshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Error & Exception Handling in Python

Error and exception handling in Python is crucial for creating


robust and reliable programs. It allows you to gracefully handle
unexpected situations, such as user input errors or issues with file
operations, without crashing the program.

Types of Errors

1. Syntax Errors: These occur when the Python parser detects


incorrect syntax. They are also called parsing errors.

print("Hello world) # Missing closing quotation mark

2. Runtime Errors (Exceptions): These occur during the


execution of the program. They include a wide range of error
types such as ZeroDivisionError, FileNotFoundError,
TypeError, etc.
Handling Exceptions

Python provides a way to handle exceptions using the try, except,


else, and finally blocks.

1. try and except: The try block contains code that might
throw an exception, and the except block contains code to
handle the exception.

try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Handling the exception
print("Cannot divide by zero!")

2. else: The else block is executed if no exception is raised in


the try block.

try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful:", result)

3. finally: The finally block is executed no matter what,


whether an exception is raised or not. It is typically used for
cleanup actions, such as closing a file.

try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close()
Catching Multiple Exceptions

You can catch multiple exceptions using multiple except blocks or


a single except block with a tuple of exceptions.

Multiple except blocks:

try:
# Code that may raise different types of exceptions
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero!")

Single except block with a tuple:

try:
num = int(input("Enter a number: "))
result = 10 / num
except (ValueError, ZeroDivisionError) as e:
print(f"An error occurred: {e}")

Raising Exceptions

You can raise exceptions using the raise statement. This is useful
for generating custom exceptions.

def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
return age

try:
check_age(-1)
except ValueError as e:
print(e)

You might also like