Python Experiment No: 6 Study and Implementation Exception Handling.
Aim:- Implementation of Exception Handling.
Theory:-
Python handles all errors with exceptions.
Theory:-
Python handles all errors with exceptions.
An exception is a signal that an error or other unusual condition has occurred. There are a number of built-in exceptions, which indicate conditions like reading past the end of a file, or dividing by zero. You can also define your own exceptions.
Raising exceptions:-
Whenever your program attempts to do something erroneous or meaningless, Python raises exception to such conduct:
>>> 1 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
This traceback indicates that the ZeroDivisionError exception is being raised. This is a built-in exception -- see below for a list of all the other ones.
Catching exceptions:-
In order to handle errors, you can set up exception handling blocks in your code. The keywords try and except are used to catch exceptions. When an error occurs within the try block, Python looks for a matching except block to handle it. If there is one, execution jumps there.
If you execute this code:
try:
print 1/0
except ZeroDivisionError:
print "You can't divide by zero, you're silly."
Then Python will print this:
You can't divide by zero, you're silly.
If you don't specify an exception type on the except line, it will cheerfully catch all exceptions. This is generally a bad idea in production code, since it means your program will blissfully ignore unexpected errors as well as ones which the except block is actually prepared to handle.
Exceptions can propagate up the call stack:
def f(x):
return g(x) + 1
def g(x):
if x < 0: raise ValueError, "I can't cope with a negative number here."
else: return 5
try:
print f(-6)
except ValueError:
print "That value was invalid."
In this code, the print statement calls the function f. That function calls the function g, which will raise an exception of type ValueError. Neither f nor g has a try/except block to handle ValueError. So the exception raised propagates out to the main code, where there is an exception-handling block waiting for it. This code prints:
That value was invalid.
Sometimes it is useful to find out exactly what went wrong, or to print the python error text yourself.
For example:
For example:
try:
the_file = open("the_parrot")
except IOError, (ErrorNumber, ErrorMessage):
if ErrorNumber == 2: # file not found
print "Sorry, 'the_parrot' has apparently joined the choir invisible."
else:
print "Congratulation! you have managed to trip a #%d error" %
ErrorNumber
print ErrorMessage
Which of course will print:
Sorry, 'the_parrot' has apparently joined the choir invisible.
Custom Exceptions:-
Code similar to that seen above can be used to create custom exceptions and pass information along with them. This can be extremely useful when trying to debug complicated projects. Here is how that code would look; first creating the custom exception class:
Code similar to that seen above can be used to create custom exceptions and pass information along with them. This can be extremely useful when trying to debug complicated projects. Here is how that code would look; first creating the custom exception class:
class CustomException(Exception):
def __init__(self, value):
self.parameter = value
def __str__(self):
return repr(self.parameter)
And then using that exception:
try:
raise CustomException("My Useful Error Message")
except CustomException, (instance):
print "Caught: " + instance.parameter
Q1) Explain General syntax for python handling.
Q2) How to raise exception handling in python.
Q3) Explain Custom exception in detail.
Comments
Post a Comment