Exception Handling
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:
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)
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.
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.
The try...except block is used to handle exceptions in Python. Here's the syntax of try...except block:
syntax:
try:
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)
OUTPUT:
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)
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.
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.
a=10
b=0
try:
except:
else:
c=a/b
print(c)
OUTPUT:
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
a=20 b=10
try:
except:
else:
c=a/b print(c)
OUTPUT:
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)
Output:
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:
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 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:
Output:
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.
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.
a =4
b =0
print(a /b)
Output:
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.
16 KeyError When the given key is not found in the dictionary to be found in,
this exception is raised.
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.
27 RuntimeError This exception is raised when an error that occurred during the
program's execution cannot be classified.
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:
Example:
a=5 b=0
print(a/b)
Output:
Example:
Output:
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']
Output:
File "expdemo.py", line 2, in print("list item is :",a [5]) IndexError: list index out of range.
Example:
a={"name":"Madhu","location":"Hyd"}
Output:
Example:
a=open("exam.py")
print(a)
Output:
In Python, we can define custom exceptions by creating a new class that is derived from the built-in
class.
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).
class InvalidAgeException(Exception):
try:
if a > 18:
print("Eligible to Vote")
else:
raise InvalidAgeException
except InvalidAgeException
Output
Enter a number: 45
Eligible to Vote
Enter a number: 14
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.