Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Python Exception Handling

Uploaded by

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

Python Exception Handling

Uploaded by

garrymane999
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Python Exception Handling

Python Exceptions

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. We will see what an exception is. Also, we will see the
difference between a syntax error and an exception

What is an 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.

Exceptions versus Syntax Errors

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.

When the interpreter identifies a statement that has an error, syntax errors occur.
Consider the following scenario:

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

SyntaxError: invalid syntax

#Python code after removing the syntax error


string = "Python Exceptions"

for s in string:
if (s != o:
print( s )

Output:

if (s != o:
^
SyntaxError: invalid syntax

The arrow in the output shows where the interpreter encountered a syntactic error.
There was one unclosed bracket in this case. Close it and rerun the program:

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.

# initialize the amount variable


marks = 10000

# perform division with 0


a = marks / 0
print(a)

Output:

ZeroDivisionError

Code
# Python code after removing the syntax error
# string = "Python Exceptions"
#
# for s in string1:
# if ('s' != 'o'):
# print(s) #NameError

We encountered an exception error after executing this code. When syntactically


valid Python code produces an error, this is the kind of error that arises. The output's
last line specified the name of the exception error code encountered. Instead of
displaying just "exception error", Python displays information about the sort of
exception error that occurred. It was a NameError in this situation. Python includes
several built-in exceptions. However, Python offers the facility to construct custom
exceptions

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.
These are just a few examples of the many types of exceptions that can occur in
Python. It’s important to handle exceptions properly in your code using try-except
blocks or other error-handling techniques, in order to gracefully handle errors and
prevent the program from crashing.

I. Exception Handling in Python

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The lets you execute code, regardless of the result of the try- and except blocks.

The cause of an exception is often external to the program itself. For example, an
incorrect input, a malfunctioning IO device etc. Because the program abruptly
terminates on encountering an exception, it may cause damage to system
resources, such as files. Hence, the exceptions should be properly handled so that
an abrupt termination of the program is prevented.

Python uses try and except keywords to handle exceptions. Both keywords are
followed by indented blocks.

Syntax:
try :
#statements in try block
except :
#executed when error in try block

The try: block contains one or more statements which are likely to encounter an
exception. If the statements in this block are executed without an exception, the
subsequent except: block is skipped.

If the exception does occur, the program flow is transferred to the except: block.
The statements in the except: block are meant to handle the cause of the exception
appropriately. For example, returning an appropriate error message.
You can specify the type of exception after the except keyword. The subsequent
block will be executed only if the specified exception occurs. There may be
multiple except clauses with different exception types in a single try block. If the
type of exception doesn't match any of the except blocks, it will remain unhandled
and the program will terminate.

The rest of the statements after the except block will continue to be executed,
regardless if the exception is encountered or not.

The following example will throw an exception when we try to devide an integer
by a string.

try:
a=5
b='0'
print(a/b)
except:
print('Some error occurred.')
print("Out of try except blocks.")

Output
Some error occurred.
Out of try except blocks.

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

# Python program to handle simple runtime error


#Python 3

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

You can mention a specific type of exception in front of the except keyword. The
subsequent block will be executed only if the specified exception occurs. There
may be multiple except clauses with different exception types in a single try block.
If the type of exception doesn't match any of the except blocks, it will remain
unhandled and the program will terminate.

Example: Catch Specific Error Type


Copy
try:
a=5
b='0'
print (a+b)
except TypeError:
print('Unsupported operation')
print ("Out of try except blocks")

Output
Unsupported operation
Out of try except blocks

As mentioned above, a single try block may have multiple except blocks. The
following example uses two except blocks to process two different exception
types:

Example: Multiple except Blocks


Copy
try:
a=5
b=0
print (a/b)
except TypeError:
print('Unsupported operation')
except ZeroDivisionError:
print ('Division by zero not allowed')
print ('Out of try except blocks')
Output
Division by zero not allowed
Out of try except blocks
However, if variable b is set to '0', TypeError will be encountered and processed
by corresponding except block.

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)
else and finally

In Python, keywords else and finally can also be used along with the try and except
clauses. While the except block is executed if the exception occurs inside the try
block, the else block gets processed if the try block is found to be exception free.

Syntax:
try:
#statements in try block
except:
#executed when error in try block
else:
#executed if try block is error-free
finally:
#executed irrespective of exception occured or not

The finally block consists of statements which should be processed regardless of


an exception occurring in the try block or not. As a consequence, the error-free try
block skips the except clause and enters the finally block before going on to
execute the rest of the code. If, however, there's an exception in the try block, the
appropriate except block will be processed, and the statements in the finally block
will be processed before proceeding to the rest of the code.

The example below accepts two numbers from the user and performs their
division. It demonstrates the uses of else and finally blocks.

Example: try, except, else, finally blocks


Copy
try:
print('try block')
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z= x / y
except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by 0 not accepted")
else:
print("else block")
print("Division = ", z)
finally:
print("finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." )

The first run is a normal case. The out of the else and finally blocks is displayed
because the try block is error-free.

Output
try block
Enter a number: 10
Enter another number: 2
else block
Division = 5.0
finally block
Out of try, except, else and finally blocks.

The second run is a case of division by zero, hence, the except block and the finally
block are executed, but the else block is not executed.

Output
try block
Enter a number: 10
Enter another number: 0
except ZeroDivisionError block
Division by 0 not accepted
finally block
Out of try, except, else and finally blocks.

In the third run case, an uncaught exception occurs. The finally block is still
executed but the program terminates and does not execute the program after the
finally block.

Output
try block
Enter a number: 10
Enter another number: xyz
finally block
Traceback (most recent call last):
File "C:\python36\codes\test.py", line 3, in <module>
y=int(input('Enter another number: '))
ValueError: invalid literal for int() with base 10: 'xyz'

# 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

You might also like