How to catch and print exceptions in Python?
An exception is an event that halts the execution of a Python program.
Exceptions in Python include ZeroDivisionError and IndexError.
By capturing an exception and reporting it, the program operation will not be halted while the error received during execution is displayed.
Example 1:
try:
a = 1/0
except Exception as e:
print(e)
Output:
division by zero
Example 2:
try:
l = [1, 2, 3]
l[4]
except IndexError as e:
print(e)
Output:
list index out of range
Place the code that may throw an exception in a try block.
To catch a particular exception, replace the Exception with the exception’s name.
Make an except block right after the try block with the line except Exception as e.
This will enable you to learn how to handle any errors that occur. The object e can also print the error.
Catch and Print IndexError
Python will throw an IndexError if you attempt to access the list element with index 100 while the list contains only three elements.
This error indicates that the list index is out of range.
Example:
try:
name = ['Jane', 'John', 'Jay']
print(name[3])
except Exception as e:
print(e)
You wrapped the function in a try/catch block and then displayed the exception, but the program is not shut down.
Therefore, the final print() statement is executed after the exception has been handled.
This is the result of the print function that is on the previous line of code.
Output:
list index out of range
Catch and Print ValueError
The ValueError
occurs if you attempt to utilize incorrect values in certain functions.
Here’s an instance where the ValueError
is thrown when the square root of a negative value was attempted to be calculated:
Example:
import math
try:
a = math.sqrt(-2)
except Exception as e:
print(e)
Output:
math domain error
You can also explore more on Python print exception ValueError with Python ValueError Exact Solution.
Catch and Print TypeError
If you use indexing with the square bracket notation on an object that is not indexable, Python will throw a TypeError
because the object is not subscribable.
If the object does not define the __getitem__()
method, this is the case.
Example:
try:
variable = None
print(variable[0])
except Exception as e:
print(e)
Output:
'NoneType' object is not subscriptable
Python Exceptions
Exceptions are events that occur during the execution of a program that interrupts the normal flow of instructions.
When a Python script reaches a scenario it cannot handle, it typically raises an exception.
The exception object in Python describes an error.
Even though a statement or phrase is syntactically correct, attempting to execute it may result in an error.
Exceptions are errors identified during execution, and they are not necessarily deadly.
Most exceptions, on the other hand, are not handled by programs and lead to the following error messages:
Example (ZeroDividionError)
10 * (1/0)
Output:
Traceback (most recent call last): File "main.py", line 1, in <module> 10 * (1/0) ZeroDivisionError: division by zero
Example (NameError)
4 + spam*3
Output:
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'spam' is not defined
Example (TypeError)
'2' + 2
Output:
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str
Exception handling in Python
Programming exceptions are conceivable.
The following example prompts the user for input until a valid integer is entered, but allows the user to interrupt the application.
A user-generated interruption raises the KeyboardInterrupt exception.
Example:
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
Output:
Please enter a number: Oops! That was no valid number. Try again... Please enter a number: Traceback (most recent call last): File "main.py", line 5, in <module> x = int(input("Please enter a number: ")) EOFError: EOF when reading a line
Here’s how the try function works:
- First, the try clause (statement(s) between try and except) run time.
- If no exception occurs, the try statement ends.
- The rest of the try clause is bypassed if an exception occurs. The except clause is run if the exception type matches the except keyword. Then the execution continues after the try/except block.
- Unlisted exceptions are sent to outer try statements. In the handler is absent, the application quits with the above message.
A try statement may have multiple except clauses to define distinct exception handlers. However, the statement only executes one handler at most.
Python Handlers only handle exceptions that occur within their respective try clause and not within other handlers of the same try statement. An except clause may provide numerous exceptions as a comma-separated tuple.
Example
except (RuntimeError, TypeError, NameError): pass
How to raise exceptions in Python?
The raise statement enables the programmer to command the occurrence of a specific exception.
Example:
raise NameError('HiThere')
Output:
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: HiThere
The exception to be raised is indicated by the lone argument “raise
“.
This must be either an instance of an exception or a class that inherits from the Exception base class.
If an exception class is passed, its constructor will be implicitly constructed with no arguments.
Example:
raise ValueError
Python chained exceptions
The raise statement supports an optional parameter, which enables exception chaining.
Example:
raise RuntimeError from exc
Note: The exc must be exception instance or None for syntax purposes.
Chaining is beneficial when transforming exceptions.
Example:
def func():
raise ConnectionError
try:
func()
except ConnectionError as exc:
raise RuntimeError('Failed to open database') from exc
Output:
Traceback (most recent call last): File "main.py", line 7, in <module> func() File "main.py", line 3, in func raise ConnectionError ConnectionError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "main.py", line 11, in <module> raise RuntimeError('Failed to open database') from exc RuntimeError: Failed to open database
User-defined exception in Python
Programs can name their exceptions by defining a new class. Exceptions should stem directly or indirectly from the exception.
Exception classes can do anything that any other class can do, but they are usually minimal and only show a few properties that handlers can use to figure out what went wrong.
Most exceptions finish in “Error,” like standard exceptions.
Many standard modules define exceptions for functions they define. By default, classes contain more information.
Summary
In summary, Python contains some built-in exceptions that pop up when an error occurs.
When these exceptions occur, the Python interpreter terminates the current process and transfers control to the process that raised the exception.
The Python print exception waits until it is handled, and without intervention, the program will crash.
Aside from this topic, you can also check the Python Ceiling Method with Examples