Error Handling in Python

Share:
There are two types of errors :
  1. Syntax Errors
  2. Exceptions
Syntax Errors occur due to invalid syntax in the program which can be avoided by practice and experience. But, the main problem is an exception that occurs at run-time execution even if the program is syntactically correct.

Errors in python


>>> 18*(2/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> "Pythonblog"+2020
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly

Exceptions are different types and the type in printed in the output. ZeroDivisionError,TypeError,NameError are some exception names.Those are built-in exceptions. User-defined exceptions also exist. The names of exceptions are built-in but not reserved keywords.

When an exception occurs in the program the remaining program will stop executing it.

f = open("filename.txt","a")
f.write("Testing the file")
print("Succesfully written into a file ")
f.close()

When the error occurred at first line by invalid filename then remaining lines of code will not execute further.

How to handle the exception

When an exception occurs in the program it will terminate. To stop this we use a few keywords like try, except, raise, and finally.

In the above example, we add a string and a number to not takes place in that situation we have to place a condition that should be an integer.

while True:
    try:
        x = int(input("Enter any number"))
        break
    except (ValueError,RuntimeError):
        print("Sorry,Only integers are allowed")

First, try clause (or) block is executed after executing this clause then if an exception occurs except clause with the type matches the exception name after the except keyword is executed by skipping the try block. If not except clause is not executed.

try, except clause have an optional else clause which, when present will follow all except clause. when it doesn't raise any error then it will execute else clause.

raise statement is used to force an exception to occur. 
If you don't want the exception to be handled re-raise the exception.

>>>try:
       raise NameError(pythonblog)
except NameError as n:
       print(n.args,"Not defined")
       raise
"pythonblog" Not defined
Traceback (most recent call last):
  File "<stdin>", line 2, in <module> 
NameError: pythonblog

finally  
finally, clause runs whether the try statement produces an exception. finally runs after executing all try blocks.

If an exception occurs while executing a try clause then an exception may be handled by the except clause if not then the exception is re-raised after executing the finally block.
>>>try:
       raise KeyboardInterrupt
finally:
       print("Python blog")

Python blog
KeyboardInterrupt
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
The error raised after executing the finally block.

To know more about user-defined exceptions you need to know about class and inheritance.

You can check the official python documentation about errors and exceptions.

Program: Using try and except clause to find the age greater than 18 

No comments

F