Exception Handling
Exception Handling
Exception Handling
• Run time errors are known as Exception.
• Whenever an exception occurs the program
halts the execution and thus further code is
not executed.
• Exception in python code can also be handled
using try-except block.
Built-in Exception
• Python has many built-in exceptions which
forces your program to output an error when
something in goes wrong.
Built-in Exception
Python has many built-in exceptions which forces your
program to output an error when something in goes wrong.
try:
code
except:
code to be executed in case exception occurs.
else:
code to be executed in case exception does not occur.
try:
a=10/0;
except:
print "Arithmetic Exception"
else:
print "Successfully Done"
Output:
>>>
Arithmetic Exception
Declaring Multiple Exception
Multiple Exceptions can be declared using the same except statement:
Syntax:
try:
code
except Exception1,Exception2,Exception3,..,ExceptionN
execute this code in case any Exception of these occur.
else:
execute code in case no exception occurred.
try:
n=int(input("enter nume"))
d=int(input("enter denom"))
div=n/d
print(div)
except (ValueError,ZeroDivisionError):
print("Value Error/Zero Division Error")
enter nume3
enter denomsam
Value Error/Zero Division Error
>>>
Finally Block:
•In case if there is any code which the user want to be
executed, whether exception occurs or not then that
code can be placed inside the finally block.
•Finally block will always be executed irrespective of
the exception.
Syntax:
try:
Code
except:
execute this code in case any Exception of these occur.
finally:
code which is must to be executed
try:
n=int(input("enter nume:"))
d=int(input("enter denom:"))
div=n/d
print(div)
except (ValueError,ZeroDivisionError):
print("Value Error/Zero Division Error")
finally:
print("Done")
enter nume:4
enter denom:2
2.0
Done
>>> ================================ RESTART
================================
>>>
enter nume:sam
Value Error/Zero Division Error
Done
>>>
Raise an Exception
Raise an Exception:
• You can explicitly throw an exception in Python using
raise statement.
• raise will cause an exception to occur and thus
execution control will stop in case it is not handled.
Syntax:
• raise [Exception,[args,[traceback]]]
>>> raise valueError
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
raise valueError
NameError: name 'valueError' is not defined
Exception with arguments
try:
statements
except ExceptionType as argument:
execute this code in case any Exception of these occur.
try:
a=int(input("enter a num:"))
b=int(input("enter a num:"))
d=a/b
print(d)
except Exception as e:
print (type(e))
>>>
enter a num:3
enter a num:0
<class 'ZeroDivisionError'>
User Defined Exception
• Some time while writing code the built in
exception types are not serving the purpose
for handling an execution.
• To handle this problem in python programmer
can write and handle their own exception.
•