0% found this document useful (0 votes)
5 views21 pages

Exception Handeling in Python

The document provides an overview of exception handling in Python, explaining the difference between exceptions and errors, and detailing the syntax and usage of try, except, else, and finally blocks. It also covers common exceptions, how to catch specific exceptions, raise exceptions, and the advantages and disadvantages of exception handling. Additionally, it includes problems for practice related to handling exceptions in Python.

Uploaded by

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

Exception Handeling in Python

The document provides an overview of exception handling in Python, explaining the difference between exceptions and errors, and detailing the syntax and usage of try, except, else, and finally blocks. It also covers common exceptions, how to catch specific exceptions, raise exceptions, and the advantages and disadvantages of exception handling. Additionally, it includes problems for practice related to handling exceptions in Python.

Uploaded by

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

Exception Handeling

What is an exception?
An exception in Python is an event that occurs
during the execution of a program that disrupts
the normal flow of the program's instructions.
When an error occurs within a Python program,
it raises an exception. If the exception is not
handled, the program will terminate and display
an error message.
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.
# 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

• 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).
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:

# Simple Exception Handling Example


n = 10
try:
res = n / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Can't be divided by zero!")
Example
try:
n=0 Explanation:
res = 100 / n try block asks for user input and
tries to divide 100 by the input
except ZeroDivisionError:
number.
print("You can't divide by zero!")
except blocks handle
except ValueError: ZeroDivisionError and
print("Enter a valid number!") ValueError.
else: else block runs if no exception
print("Result is", res) occurs, displaying the result.
finally: finally block runs regardless of
print("Execution complete.") the outcome, indicating the
completion of execution.
Output:-
You can't divide by zero!
Execution complete.
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.

Raised when a division or modulo operation is performed


ZeroDivisionError
with zero as the divisor.
Common Exceptions in Python
Exception Name Description
Raised when a numerical operation exceeds the
OverflowError maximum limit of a data type.

FloatingPointError Raised when a floating-point operation fails.

AssertionError Raised when an assert statement fails.

Raised when an attribute reference or assignment


AttributeError fails.

IndexError Raised when a sequence subscript is out of range.

KeyError Raised when a dictionary key is not found.


Common Exceptions in Python
Exception Name Description
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.

Raised when an operation or function is applied to an


TypeError
object of inappropriate type.

Raised when a function receives an argument of the right


ValueError
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 Explanation:


respond to different exception types differently. The ValueError is caught
because the string “str”
try: cannot be converted to an
x = int("str") # This will cause ValueError integer.
If x were 0 and conversion
#inverse inv = 1 / x
successful, the
except ValueError: ZeroDivisionError would be
print("Not Valid!") caught when attempting to
except ZeroDivisionError: calculate its inverse.
print("Zero has no inverse!")

Output
Not Valid!
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.

a = ["10", "twenty", 30] # Mixed list of integers and strings


try:
total = (a[0]) + (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'
a = ["10", "twenty", 30] # Mixed list of integers and strings
try:
total = (a[0]) + (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:
• The ValueError is caught when trying to convert “twenty” to an
integer.
• TypeError might occur if the operation was incorrectly applied to
non-integer types, but it’s not triggered in this specific setup.
• IndexError would be caught if an index outside the range of the list
was accessed, but in this scenario, it’s under control.
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
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:
• 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.
Advantages of Exception Handling:

• Improved program reliability: By handling exceptions properly, you


can prevent your program from crashing or producing incorrect
results due to unexpected errors or input.
• Simplified error handling: Exception handling allows you to
separate error handling code from the main program logic, making
it easier to read and maintain your code.
• Cleaner code: With exception handling, you can avoid using
complex conditional statements to check for errors, leading to
cleaner and more readable code.
• Easier debugging: When an exception is raised, the Python
interpreter prints a traceback that shows the exact location where
the exception occurred, making it easier to debug your code.
Disadvantages of Exception Handling:

• Performance overhead: Exception handling can be slower than


using conditional statements to check for errors, as the
interpreter has to perform additional work to catch and handle
the exception.
• Increased code complexity: Exception handling can make your
code more complex, especially if you have to handle multiple
types of exceptions or implement complex error handling logic.
• Possible security risks: Improperly handled exceptions can
potentially reveal sensitive information or create security
vulnerabilities in your code, so it’s important to handle
exceptions carefully and avoid exposing too much information
about your program.
Problems
1. Write a Python program to handle a ZeroDivisionError exception when
dividing a number by zero.
2. Write a Python program that prompts the user to input an integer and
raises a ValueError exception if the input is not a valid integer.
3. Write a Python program that opens a file and handles a
FileNotFoundError exception if the file does not exist.
4. Write a Python program that prompts the user to input two numbers and
raises a TypeError exception if the inputs are not numerical.
5. Write a Python program that executes an operation on a list and handles
an IndexError exception if the index is out of range.

Python Exception Handling: Exercises, Solutions, and Practice


Thank You!

You might also like