Definition
Exception Handling In Python is one of the features of OOPS. It is mainly designed to handle runtime errors and the exceptions that corrupt the flow of the program. The general format is the usage of “try” and “except” keywords. There may be some block of code that may get an error during the runtime so we run that code inside the try block and if the code gets interrupted by any errors, it leaves the block and goes to the except block.
Syntax:
try: statements except: statements
Example
try: a = 5 b = 0 print(a/b) except: print("ZeroDivision Error")
Output
ZeroDivision Error
Explanation:
In the try block, the number is divided by zero which faces an exception and moves to the except. Here, no specific error type is found, and prints the message passed in the except block.
Keywords used with Exception Handling
There are 5 keywords that are mainly used in exception handling–
- Try
- Except
- Else
- Finally
- raise
Handling Common Errors
Some of the common types of errors that can be easily handled in Python are–
- Arithmetic error – occurs when the arithmetic calculations fail.
- Overflow error – occurs when the input size exceeds the initialized size of the variable.
- Floating-point error – occurs when the calculation of floating-point values fails.
- Zero division error – occurs when the number is divided by zero.
- Import error – occurs when the import file is wrong or mismatched.
- Key error – occurs when the key is not found or mismatched in the dictionary.
- Name error – occurs when the variable name is not found or mismatched.
- Syntax error – occurs when the syntax for the logic used is wrong.
- Type Error – occurs when the data types of the variables do not match.
- IO error – occurs when the input or output acts as expected.
- Value error – occurs when the object created to store the value does not exist or fails to store the value.
Example1
try: a = 10 b = "9" print(a + b) except TypeError: print("Type error encountered")
Output
Type error encountered
Explanation
The variables a and b are of not the same type i.e. a is numeric and b is a string. Thus, there is a difference in the data type of the two variables that’s why the code execution moves to the except block where the error is identified and prints the TypeError message.
Example2
try: a=10 b='9' c=0 print(a/c) print(a+b) except TypeError: print('Type error encountered') except ZeroDivisionError: print('Tried to divide the number by zero')
Output
Tried to divide the number by zero
Explanation
Here, two statements are present, one is “dividing by zero” and “adding a number with a string“. In this case, when the first exception(a/c) is found in line 5, the flow of the program is broken and moves to the appropriate except section.
The else Keyword
The else keyword is used after the except block. The code flow is designed in such a way that, if the code does not face any exceptions/runtime errors then, it moves to the else block after executing the try block, otherwise it goes to the except block and halts the execution of the program.
Syntax:
try : statements except: statements else: statements
Now, let’s see examples–
Example1
try: a=10 b=0 c=4 print(a/c) except ZeroDivisionError: print('Tried to divide the number by zero') else: print('No exception found.. Entered else part')
Output
2.5 No exception found.. Entered else part
Explanation
The variables a and c are divided since the value of both are not 0 so it does not face exception and enter the else part.
Example2
try: a=10 b=0 c=4 print(a/b) except ZeroDivisionError: print('Tried to divide the number by zero') else: print('No exception found.. Entered else part')
Output
Tried to divide the number by zero
Explanation
Since the value of b is 0, it faces the zero division error and does not enter the else section.
The Finally Keyword
The finally keyword is placed at the end of the program. It will be executed no matter exception occurs or not.
Syntax:
try : statements except: statements finally: statements
Let’s see an example–
Example
try: a=10 b=0 c=4 print(a/b) except ZeroDivisionError: print('Tried to divide the number by zero') else: print('No exception found.. Entered else part') finally: print('Entered finally.. End of the program')
Output
Tried to divide the number by zero Entered finally.. End of the program
Explanation
The program starts with the try block, since the number is divided by zero it faces the exception. Due to the exception, it does not move to the else block but executes the finally block.
The Raise Keyword
The built-in exceptions can be handled implicitly. But, Python also allows the user to trigger the exception i.e. the user can specify at what condition of the block the exception must be carried out.
Syntax:
try: condition raise exception statements except Exception: statements
Let’s see an example–
Example
try: a=10 b=-2 if b<0: raise ValueError else: print(a/b) except ValueError: print(' Don’t divide by negative number... it will give negative result')
Output
Don’t divide by negative number... it will give negative result
Explanation
In general, the value error occurs the object created to store the value does not exist or fails to store the value, but in this code, the ValueError is triggered when the value of b is negative.
Printing the errors
If we don't know the error type and want to know the error then we can use as keyword to print the error.
Syntax:
try: # some code except Exception as e: print(e)
Now let's see some examples--
Example
try: print(12/0) except Exception as e: print(e)
Output
division by zero
Explanation
In the second line, print(12/0) will give an error so, the program execution goes to except block where we first catch the error using as keyword and stored the error in the e variable, then we simply printed the e.
Now, what if we have not used try... except... blocks, let's see--
Example
print(12/0)
Output
Traceback (most recent call last): File "/tmp/sessions/cc324f5c8863ef98/main.py", line 1, inprint(12/0) ZeroDivisionError: division by zero
Explanation
Here, we have tried to print the value which will occur due to 12/0 which is an error obviously, and the program terminates with an error, while in the above example, we have printed the error by using try-except block and as keyword.