Exception Handling ================== => In any programming language, there are 2-types of errors we have: 1) Syntax Errors 2) Run-time errors => The errors which occurs because of invalid syntax or mistake in syntax called as "Syntax errors". Ex-1: ------ x = 10 if x == 10 print("Hello") Output: ------- SyntaxError: Invalid syntax Ex-2: ------ print(10 + 20) # 30 print 10 + 20 ==> SyntaxError Note: ----- Syntax errors should be responsible by "programmers". Once all syntax errors are corrected then only the program is going to be considered for the execution. => The errors which are occurred during the execution of the program but not because of syntax (here syntax is correct) are called as "Run-time errors" => Run-time errors also called as "Exceptions". Ex-1: ----- string = "Programming" print(string[0]) # P print(string[len(string)]) # IndexError Ex-2: ----- print(10/2) # 5.0 print(10/0) # ZeroDivisionError Ex-3: ----- a = int(input("Enter value:")) print(a) Output: ------- Enter value: ten ERROR! Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'ten' What is Exception? ------------------ => An unwanted and unexpected event that disturbs normal flow of program execution is called as an "Exception". Ex: ---- a = int(input("Enter value:")) print(a/0) print(a) Output: ------- Enter value:10 ERROR! Traceback (most recent call last): File "", line 2, in ZeroDivisionError: division by zero Examples for exceptions in python are: ZeroDivisionError TypeError ValueError FileNotFoundError IndexError etc. => When we want to execute the program normally even an exception occurred then we need to handle exceptions this is the main objective of an exception handling. => Exception handling cannot repair the program this can provide the alternative way to execute the program normally. Ex: ---- Suppose we want to read a file from virtual computer which is located in "Bangalore". While executing if the Bangalore file is not available, the program can terminated abnormally. Instead if we can load the local file then the application can execute normally with alternative way. Default Exception Handling: ---------------------------- => Every exception in python is an object. For every exception there is a corresponding class. => Whenever an exception occurs, PVM will create the corresponding exception object and will check for handling code. If handling code is not available the PVM terminate the program abnormally and prints corresponding exception information to the console. And the rest of the program won't be executed after the exception statement. Ex: ---- a = int(input("Enter value:")) print(a/0) print(a) Output: ------- Enter value:10 ERROR! Traceback (most recent call last): File "", line 2, in ZeroDivisionError: division by zero Python's Exception Hierarchy: ----------------------------- BaseException Exception SystemExit GeneratorExit KeyboardInterrupt Exception AttributeError ArithmeticError EOFError NameError LookUpError OSError TypeError ValueError ArithmeticError ZeroDivisionError FloatingPointError OverFlowError LookUpError IndexError KeyError OSError FileNotFoundError InterruptedError PermissionError TimeOutError Customized Exception Handling: ------------------------------ using try-except: ----------------- code with exception ==> risky code => risky code can write in the "try block" => Handling code must be write in "except block". Ex: ---- a = int(input("Enter value:")) try: print(a/0) except ZeroDivisionError: print(a/2) print(a) => when you don't know the type of the exception then also we can handle the exception as like below: Ex: ---- a = int(input("Enter value:")) try: print(a/0) except Exception: print(a/2) print(a) try-except-finally block: -------------------------- try: risky code except: Handling code finally: cleanup code case-1: When there is no exception ------------------------------------ try: print("try") except Exception: print("Except") finally: print("finally") output: -------- try finally case-2: if there is an exception raised and handled: ---------------------------------------------------- try: print("try") print(10/0) except Exception: print("Except") finally: print("finally") Output: ------- try Except finally case-3: If there is an exception raised but not handled: --------------------------------------------------------- try: print("try") print(10/0) except NameError: print("Except") finally: print("finally") Output: ------- try finally ERROR! Traceback (most recent call last): File "", line 3, in ZeroDivisionError: division by zero Case-4: With multiple except blocks ------------------------------------ try: print("try") print(10/0) except NameError: print("Except") except IndexError: print("Index is out of range") except ZeroDivisionError: print("No number is possible to divide with zero") finally: print("finally")