Exceptional Handling-
- – Exception is a class.
- – If we will not handle the exceptions in our code then PVM will call its default exceptional handler to handle the exception.
- – One try block can have multiple except to handle the different-2 exceptions.
Format Of Using Exception Handling
- – try-except
- – try-finally
- – try-except-except
- – try-except-finally
- – try-except-except-finally
Note-
Only try without except and finally is not possible.
Ex- class Test: def main(): a = int(input("Please enter the 1st no.-")) b = int(input("Please enter the 2nd no.-")) try: c = a/b print("Result-", c) except ZeroDivisionError: print("ZeroDivisionError found") except Exception as e: print("Other error", e) finally: print("Finally called") Test.main() Output- Please enter the 1st no.-4 Please enter the 2nd no.-2 Result- 2.0 Finally called
Raise-
- – If user defined exception is there then we need to extend the behavior of parent class means Exception class.
- – At the time of object creation of user defined exception class, raise keyword is used to raise the object.
Ex-
class MyError(Exception): def __init__(self, name): self.name = name class RaiseExc: def main(): obj = MyError('User defined exception') raise obj RaiseExc.main()
-
Qsn-
How can we handle the exception in Python?
-
Ans-
We can handle the exception by two ways.
-
1) At The Time Of Definition Of Function
- 2) At the time of calling the function(Recommended to use)
1) At The Time Of Definition Of Function
Ex-
class MyError(Exception): def __init__(self, name): self.name = name class Test: def fun(): obj = MyError("Exception string") try: raise obj except MyError as ex: print("Exception found-", ex) class RaiseExc: def main(): Test.fun() RaiseExc.main() Output- Exception found- Error string
2) At The Time Of Calling The Function-
Ex-
class MyError(Exception): def __init__(self, name): self.name = name class Test: def m_test(): obj = MyError("Error string") raise obj class RaiseExc: def main(): try: Test.m_test() except Exception as ex: print("Exception found-", ex) RaiseExc.main() Output- Exception found- Error string