Updated April 17, 2023
Introduction to Python Exception Handling
The following article provides an outline for Python Exception Handling. A mechanism provided by Python, like most other object-oriented programming languages, to deal with all possible errors that may generate during the execution of a program code, with the mechanism providing a robust and effective set of methods with every error being handled in the most appropriate manner, technically being facilitated by keywords such as try and except, is termed as Python Exception Handling.
Syntax:
try:
Executes when suspicious code is executed
except Exception1:
Executed when exception 1 is raised
except Exception2:
executed when exception 2 is raised
else:
If there is no exception then execute this block.
Standard Exception List
Given below is the standard exception list:
- Exception: All exceptions base class.
- StopIteration: When no object is pointed by the next method of the iterator, this exception is raised.
- SystemExit: Hoisted through the sys.exit() function.
- StandardError: Except StopIteration and SystemExit, this acts as the base class for all built-in functions.
- ArithmeticError: For all the numeric errors, these exceptions act as the base class.
- OverflowError: This error is raised if the calculation exceeds the maximum possible value for a numeric type.
- FloatingPointError: Failure of a float operation kicks this error.
- ZeroDivisionError: Raised when a divide by zero situation occurs in the code.
- AssertionError: When the assert statement fails, then this error is triggered.
- AttributeError: When an assignment or an attribute reference fails, then it raises this error.
- EOFErroR: Raised when no more input from any of the functions and the end of the file is reached.
- ImportError: Raised while an import declaration fails.
- KeyboardInterrupt: Raised when there is an interruption to the program execution.
- LookupError: All lookup errors fall under this base class.
- IndexError: Raised when index not found.
- KeyError: Raised when the dictionary does not hold the mentioned key value.
- NameError: Raised for a missing identifier locally or globally in the program.
- UnboundLocalError: Raised when using a local variable without any value being assigned to it.
- EnvironmentError: Base class for environment-oriented errors which occur outside python.
- IOError: Raised while an input/ output process is unsuccessful.
- SyntaxError: This exception handles all python syntax-oriented errors.
- IndentationError: Improper indentation will lead to these kinds of errors.
- SystemError: This occurs in a situation when the interpreter doesn’t work as expected, but this error does not make the python program to go out of execution.
- SystemExit: When the python interpreter uses the sys.exit() function, then it leads to this exception. This makes the code abnormally terminate when not been handled properly.
- TypeError: When an operation is invalid for a particular data type, then this error is prompted.
- ValueError: When a function holds a valid type argument, but an improper value has been specified for that type of argument.
- RuntimeError: If any of the above categories are not satisfied, then this error is raised.
- NotImplementedError: Raised while a nonfigurative method that wants to be put into practice in an inherited class is not, in fact, implemented. Putting in order and managing these exceptions is a process carried out by the except block, inserted at the end of every try block.
Exception Handling Process in Python
- Except for the clause with multiple exceptions.
- Except for the clause with no exception mentioned.
- Except for the clause with Arguments.
Below we will discuss the Exception Handling Process in Python:
1. Except Clause with Multiple Exceptions
This allows more than one except statement to be declared in one except clause, and all of these declared exceptions can be raised from this except clause.
Syntax:
try:
Code block1
except(Exception1[, Exception2[,...ExceptionN]]]):
Executes when one among the exception happens
else: executed when no exception is raised
2. Except Clause with No Exception
All the exceptions triggered from the try block are capable of being processed here.
Syntax:
try:
Code block1
except:
Executes if any type of exception happens
else:
If there is no exception then execute this block.
3. Except Clause with Arguments
The actual cause of the exception will be held in the argument value.
Syntax:
try:
Code block1
except ExceptionType, Argument:
Argument value is printed here
4. Exception Handling Program
Syntax:
try:
fh = open("testfile1", "w")
try:
fh.write("Exception handeling")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
Conclusion
Every programming language holds the process of raising an exception whenever it faces an unexpected set of situations, and python is one among them which produces profound techniques for handling these exceptions, which makes it a strong base meted programming language.
Recommended Articles
We hope that this EDUCBA information on “Python Exception Handling” was beneficial to you. You can view EDUCBA’s recommended articles for more information.