0% found this document useful (0 votes)
6 views10 pages

Python Exception Handling

The document provides an overview of exception handling in Python, detailing the types of errors (syntax errors and exceptions) and common built-in exceptions such as SyntaxError, TypeError, and ZeroDivisionError. It explains how to use try and except blocks to catch and handle exceptions, as well as the use of else and finally clauses. Additionally, it discusses the advantages and disadvantages of exception handling, along with the use of arguments in exceptions for better error information.

Uploaded by

Meera
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)
6 views10 pages

Python Exception Handling

The document provides an overview of exception handling in Python, detailing the types of errors (syntax errors and exceptions) and common built-in exceptions such as SyntaxError, TypeError, and ZeroDivisionError. It explains how to use try and except blocks to catch and handle exceptions, as well as the use of else and finally clauses. Additionally, it discusses the advantages and disadvantages of exception handling, along with the use of arguments in exceptions for better error information.

Uploaded by

Meera
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/ 10

Python Exception Handling




Error in Python can be of two types i.e. Syntax errors and
Exceptions. Errors are problems in a program due to which the
program will stop the execution. On the other hand, exceptions are
raised when some internal events occur which change the normal
flow of the program.

Different types of exceptions in python:

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:
 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.
Difference between Syntax Error and
Exceptions
Syntax Error: As the name suggests this error is caused by the
wrong syntax in the code. It leads to the termination of the
program.
Example:
# initialize the amount variable
amount = 10000

# check that You are eligible to


# purchase Dsa Self Paced or not
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")

Output:

Exceptions: Exceptions are raised when the program is


syntactically correct, but the code results in an error. This error does
not stop the execution of the program, however, it changes the
normal flow of the program.

Example:
# initialize the amount variable
marks = 10000

# perform division with 0


a = marks / 0
print(a)

Output:
In the above example raised the ZeroDivisionError as we are trying
to divide a number by 0.
Note: Exception is the base class for all the exceptions in Python.
You can check the exception hierarchy here.

Example:

1) TypeError: This exception is raised when an operation or function


is applied to an object of the wrong type. Here’s an example:

x = 5
y = "hello"
z = x + y # Raises a TypeError: unsupported operand type(s) for +: 'int' and
'str'

output:
Traceback (most recent call last):
File "7edfa469-9a3c-4e4d-98f3-5544e60bff4e.py", line 4, in
<module>
z = x + y
TypeError: unsupported operand type(s) for +: 'int' and 'str'
try catch block to resolve it:

x = 5
y = "hello"
try:
z = x + y
except TypeError:
print("Error: cannot add an int and a str")

Output
Error: cannot add an int and a str

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.
Example: Let us try to access the array element whose index is out
of bound and handle the corresponding exception.
 Python3

# Python program to handle simple runtime error


#Python 3

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

Output
Second element = 2
An error occurred
In the above example, the statements that can cause the error are
placed inside the try statement (second print statement in our case).
The second print statement tries to access the fourth element of the
list which is not there and this throws an exception. This exception is
then caught by the except statement.

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. For example, we can add IndexError in the
above code. The general syntax for adding specific exceptions are –
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Example: Catching specific exceptions in the Python
# Program to handle multiple errors with one
# except statement
# Python 3

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)

# note that braces () are necessary here for


# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")

Output
ZeroDivisionError Occurred and Handled
If you comment on the line fun(3), the output will be
NameError Occurred and Handled
The output above is so because as soon as python tries to access
the value of b, NameError occurs.

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.
Example: Try with else clause
# Program to depict else clause with try-except
# Python 3
# 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)

Output:
-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)
Example:
# Python program to demonstrate finally

# No exception Exception raised in try block


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

Output:
Can't divide by zero
This is always executed

Raising Exception
The raise statement allows the programmer to force a specific
exception to occur.
# Program to depict Raising Exception

try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise # To determine whether the exception was raised or not

The output of the above code will simply line printed as “An
exception” but a Runtime error will also occur in the last due to the
raise statement in the last line. So, the output on your command line
will look like
Traceback (most recent call last):
File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in
<module>
raise NameError("Hi there") # Raise Error
NameError: Hi there

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.
How to pass argument to an Exception
in Python?



There might arise a situation where there is a need for additional
information from an exception raised by Python.
Python has two types of exceptions namely, Built-In
Exceptions and User-Defined Exceptions.
Why use Argument in Exceptions?
Using arguments for Exceptions in Python is useful for the following
reasons:
 It can be used to gain additional information about the error
encountered.

 As contents of an Argument can vary depending upon


different types of Exceptions in Python, Variables can be
supplied to the Exceptions to capture the essence of the
encountered errors. Same error can occur of different
causes, Arguments helps us identify the specific cause for
an error using the except clause.

 It can also be used to trap multiple exceptions, by using a


variable to follow the tuple of Exceptions.

Arguments in Built-in Exceptions:


The below codes demonstrates use of Argument with Built-in
Exceptions:
Example 1:

try:
b = float(100 + 50 / 0)
except Exception as Argument:
print( 'This is the Argument\n', Argument)

Output:
This is the Argument
division by zero
Example 2:
my_string = "GeeksForGeeks"
try:
b = float(my_string / 20)
except Exception as Argument:
print( 'This is the Argument\n', Argument)

Output:
This is the Argument
unsupported operand type(s) for /: 'str' and 'int'

You might also like