Exception handling in PythonBefore going into the topic, we need to understand about errors and exceptions in python and the difference between these two words. First things first, there are errors-two types of them - Syntax errors and logical errors. A syntax error occurs when the programmer did not follow the predefined syntax rules of a particular entity in the code. If the compiler finds a syntax mistake, it terminates the program and raises the error. We need to fix it. Logical errors are the mistakes the programmer makes in the logic of the code. These are not raised; instead, the mistake is to be understood when the code does not meet the purpose or problem. These are to be searched, found, and edited by the programmer and are hard to find. Now coming to the concept of exceptions: An exception is an unexpected error raised at the time of execution (not at compilation). These are not dangerous to the code; there are methods in python to handle these exceptions. Example: If we try to divide a number by 0, the compiler won't detect it as the syntax is correct. At the time of execution, the exception will be raised. Code: Output: Traceback (most recent call last): File "D:\Programs\python\exception_ex.py", line 2, in As you can observe, the last line of the message indicates the type of exception raised. There are a lot of exceptions built-in in python. The "Exception" is the base class for all the exceptions. There is a whole exception hierarchy defined in python. You can check it out online. We can handle exceptions using try and except blocks. We can also raise user-defined exceptions, which will be discussed further in the article. Using try and except statements to catch exceptions:Exceptions usually occur unexpectedly and disturb the execution of the whole code. Hence, we catch these exceptions and handle them for the execution to go smoothly. And how do we do that?
Syntax: Example program: Let's take the previous example in which Zero Division Error occurred. In the output, instead of the exception, the print statement in the "except" block will be printed: An error occurred # If we try to access an out of the bound index in an array Generally, An ArrayIndexOutOfBounds exception is raised; let's handle it There is no 4 index in the array, but we tried to access it-hence it goes into the except block and prints out the statement. Output: There is a load of built-in exceptions in python. You can check them out online. Here is a table with some of the common exceptions:
These errors are also raised in other contexts. To catch a particular Exception (try with multiple except statements)Suppose the code has a chance of raising multiple exceptions. The programmer needs to replace different exceptions with different code, i.e., if they want to handle each exception differently, there is an option for this too.
Syntax: Can consist of any number of except statements Here, we have two exceptions. Suppose we comment the second "for loop" with a Zero division error. The "except" block with the index error will be executed, and if we comment the first for loop with the index error, the except block with the zero division error is executed. Output: # Zero division error [2, 3, 5, 6] 0.6666666666666666 1.0 2.0 Oops! Division by zero #Index error [2, 3, 5, 6] The element in 0 index is: 2 The element in 1 index is: 3 The element in 2 index is: 5 The element in 3 index is: 6 Tried to access an out of bound index-check it try with else block: We can use the try-except block along with an else block. According to the syntax, the else block must be placed after all the "except" blocks. If the code in the try block is successfully executed without raising any exceptions, else block will be executed. Example program: Output: #Sample output-1-No exception rose Enter the numerator: 3 Enter the denominator: 4 The result of the division: 0.75 #Sample output-2-Exception rose Enter the numerator: 3 Enter the denominator: 0 The denominator cannot be zero "finally" keyword in python. "finally" is a keyword in python that we can use in exception handling by placing it after the else block if any, just like the name suggests. The code in the finally block is executed irrespective of any other blocks. Syntax: Example program: Output: [2, 3, 5, 6] The element in 0 index is: 2 The element in 1 index is: 3 The element in 2 index is: 5 The element in 3 index is: 6 Tried to access an out of bound index-check it You are now looking at the code in the finally block Raising our own exceptions in python:"raise" is a keyword in python, and by using a raise statement, we can raise our exceptions to stop the next statements from getting executed. Syntax: Example program snippet: Output: Don't divide by zero-check it These are generally used to create our own constraint/ exception. For example, raising an exception if the user input isn't matching the format we requested for, etc. Important point: "raise" statement without any arguments by its side is invalid and raises an error: Output: Traceback (most recent call last): File "D:\Programs\python\Raise_exception.py", line 2, in |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India