Every programmer must be familiar with errors which either stop the execution of the code in between or generate unusual or wrong outputs. On the basis of nature of errors, they can be classified into three categories:
1. Compile Time Errors
The name itself explains that these errors occur during the compile time. The main cause of compile-time errors is the Syntax of the python code.
For example, it is possible that the coder forgets to add a colon after the if statement or a closing bracket is missed. In such cases, the compiler detects the syntactical errors and the coder can correct it.
It is very easy to point out and handle the Compile time errors.
2. Logical Errors
Logical errors arise due to the implementation of an incorrect logic. In this case, the compiler will not inform you about the error like the previous one. The code will be compiled without any interruption and generate an output.
As a result of incorrect logic, the code will give you a wrong undesired output. Therefore, in order to manage the logical errors, testing and debugging of code is performed.
3. Run Time Errors
A code whose syntax is completely fine and there is no issue with logic as well, may also generate an error. This is the case of Run Time Error.
This type of error is generally caused due to the input provided by the user during runtime. For an instance, the user provides an integer value where there was the need of a string.
The best example for such an error is Division By Zero, where the user enters zero as a denominator. This input will crash the execution of the code and an exception(error) will be raised.
Usually, you may expect that no one would enter zero in the denominator.
But being a good programmer, you must take care of all the possibilities. This is where you need the concept of Exception Handling.
Try-except statement is used to handle the exceptions in Python. With the help of Exception Handling, on one hand, you can easily detect what is wrong with the process and on the other hand, the sudden crashing of the execution can be prevented.
Being the creator of the code, you might know the statements which can raise an exception(error) on receiving some exceptional input values. Such statements are known as critical statements.
TRY: To handle the exceptions, the critical statements are placed under a Try statement. Here, we ask the compiler to try to execute this critical statement.
- If it gets executed without an error, the program has no issues.
- But if the critical statement generates an error, then the control will go to the except statement instead of terminating the execution.
EXCEPT: The statements which are to be executed on the failure of the critical statement, are placed under the except statement.
FINALLY: This is the block of statement which finally gets executed, irrespective of the outcome of try or except statements. It means that the control will definitely jump to the Finally block after the execution of either try or except statement. However, it is optional to use the Finally block.
Statements to handle the exception
Statements to be executed for sure
Let us create an example without exception handling:
num = int(input('Please enter the numerator:')) den = int(input('Please enter the denominator:')) print('Result = ', num/den)
Please enter the numerator: 10 Please enter the denominator: 0 Traceback (most recent call last): File "C:/Users/TS7/AppData/Local/Programs/Python/Python37/exception.py", line 4, in <module> print('Result = ', num/den) ZeroDivisionError: division by zero
As the user gives the value of denominator as 0, the compiler generates an error ZeroDivisionError. Python interpreter shows the line of code which is generating the error i.e "
print('Result = ', num/den)". Thus, this statement is the critical statement.
Now, we will implement exception handling in the above program:
num = int(input('Please enter the numerator:')) den = int(input('Please enter the denominator:')) try: print( 'Result = ', num/den ) except Exception: print("The denominator can't be zero!!!") finally: print('Thankyou!')
Here, we have placed the critical statement in the try block.
Entering 5 as the denominator:
Please enter the numerator:10 Please enter the denominator:5 Result = 2.0 Thankyou!
- When the user enter 5 as the denominator, no error is generated. Thus, the try block is executed and Result is printed. Then the control is transferred to the finally block which displays 'Thankyou!' as output.
Entering 0 as denominator:
Please enter the numerator:10 Please enter the denominator:0 The denominator can't be zero!!! Thankyou!
- When the error is generated on giving the value of denominator as 0, the control goes to the except statement and prints a message on the screen. At last, the finally block is executed.
You can also display the name of the error generated.
except Exception as name:
Statements to handle the exception
try: a = int(input('Enter your age: ')) print(a) except Exception as y: print('Wrong input!!\n', y)
Enter your age: city Wrong input!! invalid literal for int() with base 10: 'city'
In the above example, the try block holds the variable a is intended to take an integer value. As the user enters a string 'city' instead of an integer, the control goes to the except block.
Here, we have renamed the exception as y and printed it as the output.
In most of the cases, the exceptions arise due to invalid inputs, unexpected behaviour of resources or an issue with the network or database.