Exception Handling_Python[1] [Read-Only]
Exception Handling_Python[1] [Read-Only]
Exception Handling_Python[1] [Read-Only]
Exception Handling
Course Title: Programming in Python
Course Code: BTAIML501- 20
Module: 4
Exception Handling
Exceptions
An exception is an error that occurs during the execution of a program. When an error occurs, Python
generates an exception that can be handled to prevent the program from crashing.
Example
# Division by zero raises an exception
num = 10
denom = 0
result = num / denom # This will raise a ZeroDivisionError
Types of Exceptions in python
• Bulit in Exceptions: Python has several built-in exceptions such as ZeroDivisionError, TypeError,
ValueError, IndexError, etc. These exceptions are automatically raised when a specific error occurs.
• Example:
# Example of built-in exceptions
try:
number = int("abc") # This will raise a ValueError
except ValueError:
print("Invalid input. Please enter a number.")
• User defined Exceptions: Python allows users to create their own exceptions by defining a new class
that inherits from the built-in Exception class. This is useful when you want to handle specific errors
in your application that are not covered by built-in exceptions.
• Example:
# Creating a user-defined exception
try:
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
except FileNotFoundError:
print("The file you are trying to open does not exist.")
Different Built in exceptions in python
In Python, there are several built-in Python exceptions that can be raised when an error occurs during the
execution of a program. Here are some of the most common types of exceptions in Python.
• SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code, such as a
misspelled keyword, a missing colon, or an unbalanced parenthesis.
• TypeError: This exception is raised when an operation or function is applied to an object of the wrong type,
such as adding a string to an integer.
• NameError: This exception is raised when a variable or function name is not found in the current scope.
• IndexError: This exception is raised when an index is out of range for a list, tuple, or other sequence types.
• KeyError: This exception is raised when a key is not found in a dictionary.
• ValueError: This exception is raised when a function or method is called with an invalid argument or input,
such as trying to convert a string to an integer when the string does not represent a valid integer.
• AttributeError: This exception is raised when an attribute or method is not found on an object, such as
trying to access a non-existent attribute of a class instance.
• IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails due to an
input/output error.
• ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.
• ImportError: This exception is raised when an import statement fails to find or load a module.
Error
• An error refers to a problem in the code that prevents the program from executing properly. It usually
occurs due to issues with the code or the environment. Errors are often considered irrecoverable,
meaning the program is typically terminated when an error occurs. There are two main types of errors:
a. Syntax Errors:
• Description: Occurs when there is a mistake in the syntax (rules of writing code) of the program, like
missing a colon, improper indentation, etc. These errors are detected before the program is executed
(during the parsing of the code).
• Example:
if True # Missing colon here
print("Hello")
Output
SyntaxError: invalid syntax
b. Runtime error
• Description: Occur during the execution of the program. These errors happen when the code is
syntactically correct, but an issue arises while the program is running, such as dividing by zero or
accessing an invalid index in a list.
• Example:
print(10 / 0)
Output
ZeroDivisionError: division by zero
Difference between Error and Exceptions
In the example, we are trying to divide a number by 0. Here, this code generates an exception.
To handle the exception, we have put the code, result = numerator/denominator inside the try block.
Now when an exception occurs, the rest of the code inside the try block is skipped.
The except block catches the exception and statements inside the except block are executed.
If none of the statements in the try block generates an exception, the except block is skipped.
Catching Specific Exceptions in Python
• For each try block, there can be zero or more except blocks. Multiple except blocks allow us to handle
each exception differently.
• The argument type of each except block indicates the type of exception that can be handled by it. For
example,
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.") # Output: Index Out of Bound
• In this example, we have created a list named even_numbers.
• Since the list index starts from 0, the last element of the list is at index 3. Notice the statement,
print(even_numbers[5])
Here, we are trying to access a value to the index 5. Hence, IndexError exception occurs.
When the IndexError exception occurs in the try block,
The ZeroDivisionError exception is skipped.
The set of code inside the IndexError exception is executed.
• Python try with else clause
In some situations, we might want to run a certain block of code if the code block inside try runs without
any errors.
For these cases, you can use the optional else keyword with the try statement.
Let's look at an example:
# program to print the reciprocal of even numbers
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)
Output
If we pass an odd number:
Enter a number: 1
Not an even number!
If we pass an even number, the reciprocal is computed and displayed.
Enter a number: 4
0.25
However, if we pass 0, we get ZeroDivisionError as the code block inside else is not handled by preceding
except.
Enter a number: 0
Traceback (most recent call last):
File "<string>", line 7, in <module>
reciprocal = 1/num
ZeroDivisionError: division by zero
Here, the assert statement in the code checks that num is an even number; if num is odd, it raises an
AssertionError, triggering the except block.
Python try...finally
• In Python, the finally block is always executed no matter whether there is an exception or not.
• The finally block is optional. And, for each try block, there can be only one finally block.
• Let's see an example,
try:
numerator = 10 Output:
denominator = 0 Error: Denominator cannot be 0.
This is finally block.
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is finally block.")
• In the above example, we are dividing a number by 0 inside the try block. Here, this code generates
an exception.
• The exception is caught by the except block. And, then the finally block is executed.
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.
• 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.