Exception_Handling.ipynb - Colaboratory
Exception_Handling.ipynb - Colaboratory
ipynb - Colaboratory
When a Python program meets an error, it stops the execution of the rest of the program. An error in
Python might be either an error in the syntax of an expression or a Python exception.
Exception
An exception in Python is an incident that happens while executing a program that causes the
regular course of the program's commands to be disrupted. When a Python code comes across a
condition it can't handle, it raises an exception. An object in Python that describes an error is called
an exception.
When a Python code throws an exception, it has two options: handle the exception immediately or
stop and quit.
In Python, there are several built-in 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:
1. 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.
2. 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.
3. NameError: This exception is raised when a variable or function name is not found in the
current scope.
4. IndexError: This exception is raised when an index is out of range for a list, tuple, or other
sequence types.
5. KeyError: This exception is raised when a key is not found in a dictionary.
6. 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.
7. 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.
8. IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails
due to an input/output error.
9. ZeroDivisionError: This exception is raised when an attempt is made to divide a number by
zero.
10. ImportError: This exception is raised when an import statement fails to find or load a module.
https://colab.research.google.com/drive/14342qTycaxuhpMTHtp7BOMW7nOE88Kn1#printMode=true 1/6
18/11/2023, 19:12 Exception_Handling.ipynb - Colaboratory
a = 10
if(a > 20)
print(a)
marks = 90
a = marks / 0
print(a)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-2-784fa11120fb> in <cell line: 2>()
1 marks = 90
----> 2 a = marks / 0
3 print(a)
x = 5
y = "hello"
z = x + y
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-01628386ab26> in <cell line: 3>()
1 x = 5
2 y = "hello"
----> 3 z = x + y
Try and except statements are used to catch and handle exceptions in Python. Statements that can
raise exceptions are kept inside the try clause and the statements that handle the exception are
written inside except clause.
https://colab.research.google.com/drive/14342qTycaxuhpMTHtp7BOMW7nOE88Kn1#printMode=true 2/6
18/11/2023, 19:12 Exception_Handling.ipynb - Colaboratory
except:
print ("An error occurred")
Second element = 2
An error occurred
A try statement can have more than one except clause, to specify handlers for different exceptions.
Please note that at most one handler will be executed.
try:
#statement(s)
except IndexError:
#statement(s)
except ValueError:
#statement(s)
https://colab.research.google.com/drive/14342qTycaxuhpMTHtp7BOMW7nOE88Kn1#printMode=true 3/6
18/11/2023, 19:12 Exception_Handling.ipynb - Colaboratory
def fun(a):
if a < 4:
try:
#fun(3)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
If a condition does not meet our criteria but is correct according to the Python interpreter, we can
intentionally raise an exception using the raise keyword. We can use a customized exception in
conjunction with the statement.
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-7-c95472ecc928> in <cell line: 3>()
2 num = [3, 4, 5, 7]
3 if len(num) > 3:
----> 4 raise Exception( f"Length of the given list must be less than or equal to 3
but is {len(num)}" )
Exception: Length of the given list must be less than or equal to 3 but is 4
In Python, you can also use the else clause on the try-except block which must be present after all
the except clauses. The code enters the else block only if the try clause does not raise an exception.
https://colab.research.google.com/drive/14342qTycaxuhpMTHtp7BOMW7nOE88Kn1#printMode=true 4/6
18/11/2023, 19:12 Exception_Handling.ipynb - Colaboratory
-5.0
a/b result in 0
Python provides a keyword finally, which is always executed after the try and except blocks. The
final block always executes after the normal termination of the try block or after the try block
terminates due to some exception.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
https://colab.research.google.com/drive/14342qTycaxuhpMTHtp7BOMW7nOE88Kn1#printMode=true 5/6
18/11/2023, 19:12 Exception_Handling.ipynb - Colaboratory
try:
k = 5//0 # raises divide by zero exception.
print(k)
finally:
# this block is always executed regardless of exception generation.
print('This is always executed')
1. Improved program reliability: By handling exceptions properly, you can prevent your program
from crashing or producing incorrect results due to unexpected errors or input.
2. 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.
3. Cleaner code: With exception handling, you can avoid using complex conditional statements
to check for errors, leading to cleaner and more readable code.
4. 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.
1. 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.
2. 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.
3. 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.
https://colab.research.google.com/drive/14342qTycaxuhpMTHtp7BOMW7nOE88Kn1#printMode=true 6/6