Python Exception Handling
Boost Your Career with Our Placement-ready Courses – ENroll Now
In this article, we will learn about python exception handling mechanisms. So let’s get started.
What is Exception in Python?
Any unusual situation in the program leading to an interruption in the program’s normal flow is called an exception.
In case of an exception, the program stops its exceptions, and the further lines of code are not executed. Therefore exceptions are the runtime errors that cannot handle the python script. An exception is a python object to substitute an error.
Python defines ways to handle exceptions to execute the code without frequent halting. This is known as exception handling. If we do not handle these exceptions, the interpreter does not execute any code after the error.
Python states various built-in exceptions that allow our program to run without any interruption and produce an output.
Common exceptions in Python
Below is a list of the common standard exceptions frequently thrown from a standard python program when programmers write a piece of code in Python.
1. Exception: The base class for all exceptions.
2. StopIteration: raise when iteration ends.
3. SystemExit: raised by sys.exit().
4. StandardError: base class for built-in exceptions except for the StopITeration and SystemExit.
5. ArithmeticError: happens because of numeric miscalculations.
6. overflowError: occurs when storage exceeds the limit values.
7. FloatingPointError: error caused because of the internal representation of floating numbers.
8. AssertionError: occurs when the asset condition becomes false.
9. AttributeError: happens when reference to attributes fails.
10. importError: occurs when there is an issue in importing files into python code.
11. IndexError: this happens when you try to access elements that are not in the range of the index.
12. keyError: this happens when you try to access a key not found in the dictionary.
13. nameError: this occurs when you use an invalid name.
14. SyntaxError: occurs during the translation of source code into bytecode.
15. TypeError: it occurs when you enter the wrong data type.
16. ValueError: raised when a user enters an invalid value.
17. Runtime Error: raised when the compiler encounters an error during the execution of the program.
18. ZeroDivisionError: thrown when we divide a number with zero.
19. NameError: occurs when a name is not found. It could be local or global.
20. IndentationError: it occurs when the wrong indentation is given.
21. IOError: occurs in the failure of an input-output operation.
22. EOFError: occurs when you continue to perform operations even after reaching the file’s end.
23. KeyboardInterrupt: we halt the execution of the program on hitting the CTRL+ C together
24. LookupError: it is the base class for all the errors
25. Unbound local Error: when we try to access the variable inside a function and it has not been assigned any value
26. Environment error: exceptions beyond the python variables use this as base class
27. System Exit: when you want to pause the running programming and raise an error
28. NotimplementedError: this error is raised whenever the abstract method is not in the required class to override it.
The problem without handling exceptions
An exception is an abnormal condition that causes the program to terminate.
Let’s suppose we have two variables, a and b. Taking these as input from the user, we divide a by b to print the result of the division. Suppose the user gives the value of b as zero. The program halts, and it throws an error.
Consider the piece of code:
a=int(input(“enter the value of a”)) b=int(input(“enter the value of b”)) c=a/b print(c)
The above code gives the following output:
enter the value of b 0
runfile(‘C:/Users/qures/.spyder-py3/myfirstcode.py’, wdir=’C:/Users/qures/.spyder-py3′)
Traceback (most recent call last):
File “C:\Users\qures\.spyder-py3\myfirstcode.py”, line 9, in <module>
c=a/b
ZeroDivisionError: division by zero
Difference between syntax errors and exceptions in Python
Syntax errors
These errors happen due to the wrong syntax in the code. It causes an immediate termination of the program.
Have a look at this example:
amount=10000 if(amount>2999) print("exceeding amount boundaries")
When you run the following program, you get the following error output:
The reason this error is displayed is that there is no semicolon after the if statement.
Exceptions in Python
An exception will likely be raised when the code is correct in syntax but causes an error. This does not cause a halt in the execution of the program. Instead, it transforms the normal flow of the program.
Example:
amount=10000 a=amount/0 print(a)
This code gives the following error output:
Exception Handling in Python
Python raises its own built-in exceptions when its program encounters an error. On the occurrence of these exceptions, Python terminates the current process and moves it to the calling process to handle the exception. If the process fails to handle the exception, the program crashes.
For example, consider three processes, X, Y and Z. If an error occurs in Z and is not handled by Z, then it passes it on to Y and X.
If the exception is never handled, an error message pops up, and the program halts unexpectedly.
Else with try-except
You can add an else-block along with the try-except block. Then, if there is no exception in the try- block, the code in else-block executes.
Catching exceptions in Python
Try statement handles exceptions in Python. The critical statements that could cause an error in the program are in the try clause. The except clause handles the exception raised by the try clause.
Consider a simple example:
try: print(x) except: print(“exception occurred”)
Output:
Catching specific exceptions in Python
It is not a good practice in programming to mention and handle all the exceptions within a program in one way. Each error has a distinct origin and needs to be handled differently.
A try clause has many exceptions, and each except clause handles a specific exception. A tuple of values is used to specify multiple exceptions in an except clause.
Here is an example:
try: print(x) except NameError: print(“undefined variable”) except: print(“something went wrong”)
This gives the output as:
Exception statement with exception variable
Using the ‘as’ keyword, we can also use an exception variable along with the exception statement. This object returns the reason for the exception.
Consider the following example:
a=int(input(“enter a”)) b=int(input”enter b”)) c=a/b print(c) except exception as e: print(“division by zero”) print(e) else: print(“this is else block”)
This gives the output as:
Enter b: 0
Division by zero
Raising exceptions in Python
Python programs raise exceptions when a runtime error occurs. We use the raise keyword to raise an error manually.
We can also optionally pass values to the exception to state what exception is encountered.
You can choose to throw an exception using the raise keyword. Here is an example:
x=-1 if x<0: raise exception(“Sorry, no numbers below zero”)
Output
File “demo_ref_keyword_raise.py”, line 4, in <module>
raise Exception(“Sorry, no numbers below zero”)
Exception: Sorry, no numbers below zero
Raising exceptions with an argument in Python
Using arguments while raising an exception in Python helps gain extra information about the type of error encountered.
Here, consider an example:
try: b= float(100+ 50/0) except exception as argument: print("this is the argument section")
Output:
Custom exceptions- Define your own exceptions in Python
In Python, we can create our own custom exceptions that can be raised when we encounter a specific error in the code. Consider the following example:
Class ErrorInCode(exception): Def __init__(self,data): self.data=data Def __str__(self): Return repr(self.data) try: raise errorInCode(2000) except errorInCode as e: print(“error received:”,e.data)
The output is as follows:
Try with the else clause
Suppose you want to run a particular block of code if the code inside the try runs without any errors. In such situations, you can use the else keyword with the try statement.
The else clause executes when no errors are raised.
Consider an example:
try: print(“hello”) except: print(“something went wrong”) else: print(“nothing went wrong”)
Output:
Nothing went wrong
Example:
nums=[1,2,3] try: print(nums[3]) except: print("index out of range") else: print(nums[1])
Output:
Finally Clause in Python
Code inside the ‘finally’ clause is executed regardless of whether or not the try block raises an error. In some circumstances, we want a block of code to execute irrespective of an error, such as in security systems, we want the system to log out after every session.
Example:
try: print(x) except: print(“something went wrong”) finally: print(“finally clause”)
Output:
Finally clause
BaseException in Python
The BaseException extends all errors, so we use this as a wildcard to handle any exception that we come across. But this should be used with caution as it can also hide any case of extreme errors. We can also use it to print an error message and then re-raise the exception.
AssertionError exception in Python
The assertion statements are supposed to assert if a condition is true; if it is not, then it raises an assertion error. This halts the program execution.
And if the assertion statement is true, then the program keeps running. Or, in case the condition is not true, then it raises the assertionError exception. This is one of the in-built exceptions.
Assert statement
Assert statements in python are used to examine the adjacent expressions. And if the statement is false then an assertionError exception is raised.
Raise with an argument in Python
You can also write a specific argument to that exception that displays the argument in case of an exception.
This argument will give extra details about the exception that helps you understand your exception better.
Conclusion:
So this was it about the python exception handling. We learnt about the different clauses in Python, such as the try, except and finally clauses. We hope our article was easy to understand.