0% found this document useful (0 votes)
17 views15 pages

Exception Handling

The document provides an overview of Python exception handling, detailing the types of errors (syntax errors and exceptions) and how to manage them using try, except, else, and finally blocks. It explains context management for resource handling and introduces raising exceptions and assertions. Additionally, it lists standard exceptions and demonstrates how to define custom exceptions in Python.

Uploaded by

Priksha Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views15 pages

Exception Handling

The document provides an overview of Python exception handling, detailing the types of errors (syntax errors and exceptions) and how to manage them using try, except, else, and finally blocks. It explains context management for resource handling and introduces raising exceptions and assertions. Additionally, it lists standard exceptions and demonstrates how to define custom exceptions in Python.

Uploaded by

Priksha Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Python Exception Handling

Error in Python can be of two types i.e. Syntax errors and Exceptions.Errors are the problems in a
program due to which the program will stop the execution.Exceptions are raised when the program is
syntactically correct, but the code resulted in an error. This error does not stop the execution of the
program, however, it changes the normal flow of the program.

Example of error:

a=10

prnt(a)

output:

NameError: name ‘prnt’ is not defined

In the above example instead of writing ‘print’ i written ‘prnt’ which is known error. Example of Exception:

a=10

b=0

c=a/b

print(c)

output: ZerodivisionError : Division by zero

We encountered an exception error after executing above code. Because we cannot divide any number
by zero. This error does not stop the execution of the program, however, it changes the normal flow of
the program.

Python Exception Handling (try..except..finally)

We know that exceptions abnormally terminate the execution of a program. This is why it is important
to handle exceptions. In Python, we use the

try...except block.

Python try...except Block

The try...except block is used to handle exceptions in Python. Here's the syntax of try...except block:

syntax:

try:

# code that may cause exception except:

# code to run when exception occurs

Here, we have placed the code that might generate an exception inside the try block. Every try block is
followed by an except block.

When an exception occurs, it is caught by the except block. The except block cannot be used without
the try block.
Example: Exception Handling Using try...except

a=10

b=0 try:

except:

c=a/b print(c)

print(“error , b value cant be 0 “)

OUTPUT:

error , b value cant be 0

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, c=a/b 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.

Example2:

a=20

b=10

try:

except:

c=a/b print(c)

print(“error , b value cant be 0 “)

output:

from the above example ,i will get output 2 , because If none of the statements in the try block generates
an exception, it will print code inside try block .so it will write value of c i.e., 2 and except block is skipped.

For each try block, there can also be multiple except blocks.

Python try with else

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.

Example: Exception Handling Using try...except and else block.

a=10

b=0
try:

except:

else:

c=a/b

print(c)

print(“error , b value cant be 0 “)

print(“ try block is working”)

OUTPUT:

error , b value cant be 0

In the above example,if no exception occurs then it will print both try and else block. If exception occurs
then it will skip try and else block and it print only except block

Example2 : Exception Handling Using try...except and else block.

a=20 b=10

try:

except:

else:

c=a/b print(c)

print(“error , b value cant be 0 “) print(“ try block is working”)

OUTPUT:

try block is working

In the above example, no exception occurs so it will print both try and else 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.

Example:

a=10

b=0

try:

except:

finally:
c=a/b print(c)

print(“error , b value cant be 0 “)

print(“this finally block “)

Output:

error , b value cant be 0 this finally block

Context Management in Python

In any programming language, the usage of resources like file operations or database connections is
very common. But these resources are limited in supply. Therefore, the main problem lies in making
sure to release these resources after usage. If they are not released then it will lead to resource leakage
and may cause the system to either slow down or crash. It would be very helpful if users have a
mechanism for the automatic setup and Tear down of resources. In Python, it can be achieved by the
usage of context managers which facilitate the proper handling of resources.

Program:

a = open("hello.txt", "w")

a.write("Hello, World!")

a.close()

in the above example , if exception occurs while writing text “ hello world” then it will stop execution and
it will not close file. so, This implementation doesn’t guarantee the file will be closed if an exception
occurs .

In Python, you can use two general approaches to deal with resource management. You can wrap your
code in:

1. A try … finally construct

2. A with construct
The try … finally Approach

Working with files is probably the most common example of resource management in programming. In
Python, you can use a try … finally statement to handle opening and closing files properly:

example:

a = open("hello.txt", "w")

try:

a.write("Hello, World!")

finally:

a.close()

from the above example try … finally Approach will safely opens file and automatically closes a file.
Even if exception occurs while writing “hello, world!” it will automatically close my file.

The with Statement Approach

The Python with statement creates a runtime context that allows you to run a group of statements
under the control of a context manager.

Compared to traditional try … finally constructs, the with statement can make your code clearer, safer,
and reusable. Many classes in the standard library support the with statement. A classic example of
this is open(), which allows you to work with file objects using with.

The context manager object results from evaluating the expression after with. In other words,
expression must return an object that implements the context management protocol. This protocol
consists of two special methods:

1_ _ enter_ _() is called by the with statement to enter the runtime context.

2_ _exit_ _ () is called when the execution leaves the with code block.

Example:

a= open("hello.txt", "w")

with a:

a.write("Hello, World!")

from the above example with statement approach will safely opens file and automatically closes a file.
Even if exception occurs while writing “hello, world!” it will automatically close my file. there is no need
of writing a.close() because it will automatically close my file.
Raising Exceptions

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.

If we wish to use raise to generate an exception when a given condition happens, we may do so as
follows:

example:

a=[1,2,3,4,5,6]

if len(a)>4:

raise Exception(“error!!!!! length of list must be less than 3”)

Output:

Exception:error!!!! length of list must be less than 3

Assertions :

Assertions in any programming language are the debugging tools that help in the smooth flow of code.

assert in Python

In simpler terms, we can say that assertion is the boolean expression that checks if the statement is
True or False. If the statement is true then it does nothing and continues the execution, but if the
statement is False then it stops the execution of the program and throws an error.

Flowchart of Python Assert Statement

In python, assert keyword helps in achieving this task. This statement takes as input a boolean
condition, which when returns true doesn’t do anything and continues the normal flow of execution,
but if it is computed to be false, then it raises an AssertionError along with the optional message
provided.
Syntax : assert condition, error_message(optional)

Parameters :

condition : The boolean condition returning true or false. error_message : The optional argument to be
printed in console in case of AssertionError

Returns :

Returns AssertionError, in case the condition evaluates to false along with the error message which
when provided.

Example 1: Python assert keyword without error message

Example 2: Python assert keyword with error message

a =4

b =0

print("The value of a / b is : ")

assertb !=0, "Zero Division Error"

print(a /b)

Output:

AssertionError: Zero Division Error

Standard Exceptions List


Here is the complete list of Python in-built exceptions.

Sr.No. Name of the Exception Description of the Exception

1 Exception All exceptions of Python have a base class.

2 StopIteration If the next() method returns null for an iterator, this


exception is raised.

3 SystemExit The sys.exit() procedure raises this value.

4 StandardError Excluding the StopIteration and SystemExit, this is the base


class for all Python built-in exceptions.

5 ArithmeticError All mathematical computation errors belong to this base class.

6 OverflowError This exception is raised when a computation surpasses the


numeric data type's maximum limit.

7 FloatingPointError If a floating-point operation fails, this exception is raised.


8 ZeroDivisionError For all numeric data types, its value is raised whenever a number
is attempted to be divided by zero.

9 AssertionError If the Assert statement fails, this exception is raised.

10 AttributeError This exception is raised if a variable reference or assigning a value


fails.

11 EOFError When the endpoint of the file is approached, and the interpreter
didn't get any input value by raw_input() or input() functions, this
exception is raised.

12 ImportError This exception is raised if using the import keyword to import a


module fails.

13 KeyboardInterrupt If the user interrupts the execution of a program, generally by


hitting Ctrl+C, this exception is raised.

14 LookupError LookupErrorBase is the base class for all search errors.

15 IndexError This exception is raised when the index attempted to be


accessed is not found.

16 KeyError When the given key is not found in the dictionary to be found in,
this exception is raised.

17 NameError This exception is raised when a variable isn't located in either


local or global namespace.

18 UnboundLocalError This exception is raised when we try to access a local variable


inside a function, and the variable has not been assigned any
value.

19 EnvironmentError All exceptions that arise beyond the Python

environment have this base class.

20 IOError If an input or output action fails, like when using the print
command or the open() function to access a file that does not
exist, this exception is raised.

22 SyntaxError This exception is raised whenever a syntax error occurs in our


program.

23 IndentationError This exception was raised when we made an improper


indentation.

24 SystemExit This exception is raised when the sys.exit() method is used to


terminate the Python interpreter. The parser exits if the situation
is not addressed within the code.

25 TypeError This exception is raised whenever a data type- incompatible


action or function is tried to be executed.
26 ValueError This exception is raised if the parameters for a built- in method
for a particular data type are of the correct type but have been
given the wrong values.

27 RuntimeError This exception is raised when an error that occurred during the
program's execution cannot be classified.

28 NotImplementedError If an abstract function that the user must define in an inherited


class is not defined, this exception is raised.

Python supports various built-in exceptions, the commonly used exceptions are

• NameError: It occurs when a name is not found. i.e attempt to access an undeclared variable

Example:

a=5 c=a+b

print("Sum =",c)

Output:

Traceback (most recent call last):

File "expdemo.py", line 2, inc=a+b NameError: name 'b' is not defined

• ZeroDivisionError: Occurs when a number is divided by zero.

Example:

a=5 b=0

print(a/b)

Output:

Traceback (most recent call last):

File "expdemo.py", line 3, inprint(a/b)ZeroDivisionError: division by zero

• ValueError: Occurs when an inappropriate value assigned to variable.

Example:

a=int(input("Enter a number :")) b=int(input("Enter a number : ")) print("Sum=",a+b)

Output:

Enter a number : 23 Enter a number : abc

Traceback (most recent call last):

File "expdemo.py", line 2, in b=int(input("Enter a number : ")) ValueError: invalid literal for int() with base
10: 'abc'
• IndexError: Occurs when we request for an out-of-range index for sequence

Example:

a=['c','java','python']

print("list item is :",a[5])

Output:

Traceback (most recent call last):

File "expdemo.py", line 2, in print("list item is :",a [5]) IndexError: list index out of range.

• KeyError: Occurs when we request for a non-existent dictionary key

Example:

a={"name":"Madhu","location":"Hyd"}

print("The age is :",a["age"])

Output:

Traceback (most recent call last):

File "expdemo.py", line 2, in print("The age is :",a["age"]) KeyError: 'age'

• IOError: Occurs when we request for a non-existent input/output file.

Example:

a=open("exam.py")

print(a)

Output:

Traceback (most recent call last):

File "expdemo.py", line 1, in a=open("exam.py")

FileNotFoundError: [IOError] No such file or directory:'exam.py'

Defining Custom Exceptions:

In Python, we can define custom exceptions by creating a new class that is derived from the built-in
class.

Here's the syntax to define custom exceptions,

class CustomError(Exception):

...

pass
try:

...

except CustomError:

Here, CustomError is user defined error which inherit from the Exception class

NOTE:

• When we are developing a large Python program, it is a good practice to place all the user-defined
exceptions that our program raises in a separate file.

• Many standard modules define their exceptions separately as exception.py or errors.py (generally but
not always).

User defined exception

#define Python user-defined exceptions

class InvalidAgeException(Exception):

"Raised when the input value is less than 18" pass

a = int(input("Enter a number: "))

try:

if a > 18:

print("Eligible to Vote")

else:

raise InvalidAgeException

except InvalidAgeException

print("Exception occurred: Invalid Age")

Output

If the user input input_num is greater than 18,

Enter a number: 45

Eligible to Vote

If the user input input_num is smaller than 18,

Enter a number: 14

Exception occurred: Invalid Age


In the above example, we have defined the custom InvalidAgeException exception built-in Exception
class. by creating a new class that is derived from the built in exception class. Here, when is smaller
than 18, this code generates an exception.

When an exception occurs, the rest of the code inside the try block is skipped. InvalidAgeException

except The block catches the user-defined exception and statements inside the block are executed.

You might also like