Python Tutorial
#!/usr/bin/python a = 10 result = 0 try: result = a/0 except ZeroDivisionError as ex: print("Exception: %s" % ex) print resultOutput:
$ python exception_test.py Exception: integer division or modulo by zero 0
#!/usr/bin/python a = 10 result = 0 try: result = a/0 except ZeroDivisionError as ex: print("Exception: %s" % ex) # raises the same exception using alias name raise ex print resultOutput:
$ python exception_test.py Exception: integer division or modulo by zero Traceback (most recent call last): File "exception_test.py", line 9, inraises exception using corresponding exception class or custom exception.raise ex ZeroDivisionError: integer division or modulo by zero
#!/usr/bin/python a = 10 result = 0 try: #result = a/0 raise ZeroDivisionError("Divide by zero error") except ZeroDivisionError as ex: print("Exception: %s" % ex) #raise ex print resultOutput:
$ python exception_test.py Exception: Divide by zero error 0
#!/usr/bin/python a = [10, 20, 30, 40, 50] result = 0 try: result = a[6]/0 except (IndexError, ZeroDivisionError) as ex: print("Exception: %s" % ex) print resultOutput:
$ python exception_test1.py Exception: list index out of range 0
#!/usr/bin/python a = [10, 20, 30, 40, 50] result = 0 try: result = a[6]/0 except IndexError as ex: print("Index Error: %s" % ex) except ZeroDivisionError as ex: print("Zero Division Error: %s" % ex) print resultOutput:
$ python exception_test2.py Index Error: list index out of range 0
#!/usr/bin/python a = 10 result = 0 try: result = a/0 except ZeroDivisionError as ex: print("Exception: %s" % ex) finally: print("finally block") print resultOutput:
$ python finally_test.py Exception: integer division or modulo by zero finally block 0
#!/usr/bin/python a = 10 result = 0 try: result = a/10 except ZeroDivisionError as ex: print("Exception: %s" % ex) else: print("ZeroDivisionError is not occurred") print resultOutput:
$ python try_else_test.py ZeroDivisionError is not occurred 1
class CustomError(Exception): """Custom Failure"""Example:
#!/usr/bin/python # Custom exception creation class DivideByZeroError(Exception): """Custom Failure""" a = 10 result = 0 try: #result = a/0 # raises custom exception raise DivideByZeroError("Divide by zero error") except DivideByZeroError as ex: print("Exception: %s" % ex) #raise ex print resultOutput:
$ python exception_test.py Exception: Divide by zero error 0
Python Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page