Exception Handling in Python
Any mistakes may be made when writing a program that will lead to errors when the user tries to execute it. As soon as it finds an unhandled bug, a python program terminates. It is possible to divide these errors broadly into two classes:
Syntax Errors
Logical Errors
Syntax Errors
Any mistake caused by failure to obey the accurate language structure (syntax) is called a syntax error or a parsing error.
Logical Errors
Exceptions or logical errors are considered errors arising at runtime (after passing the syntax test).
For example, when a user attempts to open a file that does not exist (FileNotFoundError), tries to break a number by zero (ZeroDivisionError), or tries to import a module that does not exist, they occur (ImportError).
Python generates an exception object if certain kinds of runtime errors arise. If not handled correctly and any information on why the mistake happened, it prints a traceback to the error.
Built-in Exceptions in Python
Illegal operations may give rise to exceptions. In Python, there are lots of built-in cases that are raised when critical errors occur. Using the built-in local() function, it would display all the built-in exceptions as follows:
locals()[‘builtins’] will return a module of built-in exceptions, functions, and attributes. Dir enables one to list strings of these attributes.
Some of the standard built-in exceptions in Python programming are mentioned below, along with the bug that causes them.
Exception | Cause of Error |
AssertionError | Raised when an assert statement fails. |
AttributeError | Raised when attribute reference fails. |
EOFError | It occurs when input() function hits the condition end-of-file. |
FloatingPointError | It occurs when operation fails on a floating-point. |
NameError | It raises when the compiler is not able to locate a variable in the local or global scope. |
Python manages these built-in and user-defined exceptions using attempt, except for statements and finally.
Python Exceptions
In Python, there are several built-in exceptions when an error happens in the software (something in the program goes wrong).
The Python interpreter interrupts the current process as these exceptions exist and move it to the calling process before it is treated. The software would fail if not handled.
Let’s consider a program, for instance, where the user has a function A that calls function B, which in turn calls function C. The exception moves to B and then to A if an exception exists in function C but is not treated in C.
Catch Exceptions in Python
Exceptions can be managed in Python by using a try statement. Inside the try clause, the essential operation which can raise an exception is put. In the exception clause, the code that manages the exceptions is written.
Users may then select what operations to run. Here is a simple example.
# import module sys to get the type of exception import sys randomList = ['a', 0, 2] for entry in randomList: try: print("The entry is", entry) r = 1/int(entry) break except: print("Oops!", sys.exc_info()[0], "occurred.") print("Next entry.") print() print("The reciprocal of", entry, "is", r)
User loops through the values of the array in the program. It skips the exception block, and regular flow resumes if no exception exists (for last value). However, if an exception exists, it captures by the block except (first and second values). Since Python inherits the exception from the base Exception class, here is another example to perform the above-mentioned program.
# import module sys to get the type of exception import sys randomList = ['a', 0, 2] for entry in randomList: try: print("The entry is", entry) r = 1/int(entry) break except Exception as e: print("Oops!", e.__class__, "occurred.") print("Next entry.") print() print("The reciprocal of", entry, "is", r)
Output:
The entry is a Oops! <class 'ValueError'> occurred. Next entry. The entry is 0 Oops! <class 'ZeroDivisionError'> occured. Next entry. The entry is 2 The reciprocal of 2 is 0.5
Other useful articles:
- OOP in Python
- Python v2 vs Python v3
- Variables, Data Types, and Syntaxes in Python
- Operators, Booleans, and Tuples
- Loops and Statements in Python
- Python Functions and Modules
- Regular Expressions in Python
- Python Interfaces
- JSON Data and Python
- Pip and its Uses in Python
- File Handling in Python
- Searching and Sorting Algorithms in Python
- System Programming (Pipes &Threads etc.)
- Database Programming in Python
- Debugging with Assertion in Python
- Sockets in Python
- InterOp in Python
- Exception Handling in Python
- Environments in Python
- Foundation of Data Science
- Reinforcement Learning
- Python for AI
- Applied Text Mining in Python
- Python Iterations using Libraries
- NumPy vs SciPy
- Python Array Indexing and Slicing
- PyGame
- PyTorch
- Python & Libraries