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

Exception_Handling.ipynb - Colaboratory

The document provides an overview of exception handling in Python, explaining what exceptions are and how they disrupt program execution. It details common types of exceptions, how to catch and handle them using try and except statements, and the use of else and finally clauses. Additionally, it discusses the advantages and disadvantages of exception handling in programming.

Uploaded by

Shreya Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Exception_Handling.ipynb - Colaboratory

The document provides an overview of exception handling in Python, explaining what exceptions are and how they disrupt program execution. It details common types of exceptions, how to catch and handle them using try and except statements, and the use of else and finally clauses. Additionally, it discusses the advantages and disadvantages of exception handling in programming.

Uploaded by

Shreya Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

18/11/2023, 19:12 Exception_Handling.

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.

Different types of Exceptions

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)

File "<ipython-input-1-433b7d4b436d>", line 2


if(a > 20)
^
SyntaxError: expected ':'

SEARCH STACK OVERFLOW

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)

ZeroDivisionError: division by zero

SEARCH STACK OVERFLOW

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

TypeError: unsupported operand type(s) for +: 'int' and 'str'

SEARCH STACK OVERFLOW

Try and Except Statement – Catching Exceptions

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

# Python program to handle simple runtime error


a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))

# Throws error since there are only 3 elements in array


print ("Fourth element = %d" %(a[3]))

except:
print ("An error occurred")

Second element = 2
An error occurred

Catching Specific Exception

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.

The general syntax for adding specific exceptions are –

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:

# throws ZeroDivisionError for a = 3


b = a/(a-3)

# throws NameError if a >= 4


print("Value of b = ", b)

try:
#fun(3)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")

NameError Occurred and Handled

How to Raise an Exception

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.

#Python code to show how to raise an exception in Python


num = [3, 4, 5, 7]
if len(num) > 3:
raise Exception( f"Length of the given list must be less than or equal to 3 but is {len(

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

SEARCH STACK OVERFLOW

Try with Else Clause

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

# Program to depict else clause with try-except


# Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)

# Driver program to test above function


AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

-5.0
a/b result in 0

Finally Keyword in Python

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:

# Some code .....(always executed)

https://colab.research.google.com/drive/14342qTycaxuhpMTHtp7BOMW7nOE88Kn1#printMode=true 5/6
18/11/2023, 19:12 Exception_Handling.ipynb - Colaboratory

# Python program to demonstrate finally

try:
k = 5//0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed regardless of exception generation.
print('This is always executed')

Can't divide by zero


This is always executed
Advantages of Exception Handling:

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.

Disadvantages of Exception Handling:

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

You might also like