In this article, we will discuss about what is exception handling , different types of exception handling and how to handle exceptions. Exception Handling helps in identifying errors that occurs during program execution.
Python Errors
Basically in Python errors are classified into two types i.e. Syntax error, Exceptions
- Syntax Error : These type of error occur when code violates the rules or structure. For example, missing colons(:), using invalid characters like special symbols except underscore (_),incorrect indentation.
- Exceptions: These type of errors occur during the execution of the program. They can cause due to invalid user input, runtime error, accessing undefined files or variables.
Different types of Exceptions
An exception can be defined as an abnormal condition in a program resulting in disturb in the natural flow of the program.
There are two types of exceptions:
- System defined exception
- User defined exception
System defined exception
These exceptions are predefined errors there are few examples of built-in exceptions to cover various error scenarios
- ZeroDivisionError: Occurs when a number is divided by zero.
- NameError: Occurs when a name is not found. It may be local or global.
- IndentationError: Occurs if there is incorrect indentation is given.
- IOError: Occur when input and output operation fails.
- EOFError: Occur when end of the file is reached, and yet operations are being performed.
- TypeError: Occurs when operation or function is performed to a wrong type example adding a string to an integer
- ImportError: This exception is raised when an import statement fails to find or load a module.
- ValueError: This exception occurs when a function or method is called with an invalid argument or input
- FileNotFoundError: Occurs when a file or directory is requested but cannot be found.
- KeyError: Occurs when dictionary key is not found.
User defined exception
User defined exceptions in Python are exceptions that are created by the programmers to handle specific error conditions within the code.
Handling Exceptions:
- ZeroDivisionError: Occurs when a number is divided by zero.
a=4 b=0 c=a/b print(a)
Output: ERROR! Traceback (most recent call last): File "<main.py>", line 3, in <module> ZeroDivisionError: division by zero
=== Code Exited With Errors ===
- TypeError: Occurs when operation or function is performed to a wrong type example adding a string to an integer
a=4 b=5 c=a/'b' print(a)
Output: Traceback (most recent call last): File "<main.py>", line 3, in <module> TypeError: unsupported operand type(s) for /: 'int' and 'str'
- NameError: Occurs when a name is not found. It may be local or global.
a=14 b=5 c=a/d print(c)
Output: ERROR! Traceback (most recent call last): File "<main.py>", line 3, in <module> NameError: name 'd' is not defined
- SyntaxError: This exception is occurs when the interpreter encounters a syntax error in the code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
a =int(input("enter number")) if(age >= 18) print("You are eligible to vote")
Output: Traceback (most recent call last): File "<main.py>", line 2 if(age >= 18) ^ SyntaxError: expected ':'
- IndexError: Occurs when request for an out of range index sequence
alist=[1,2] alist[4]
Output: ERROR! Traceback (most recent call last): File "<main.py>", line 2, in <module> IndexError: list index out of range
Statement Exceptions
Try and except statements are used to handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause
Syntax
try: #block of code
except(<Expression 1>,<Expression 2>,<Expression 3>……<Expression n>) #block of code
a = [1, 2, 3,] try: print ("element = %d" %(a[1])) print ("Fourth element = %d" %(a[3])) except: print ("error occurred")
Output: element = 2 error occurred === Code Execution Successful ===
Else block:
We can also use the else statement with the try-except statement in which, we can place the code if no exception occurs in the try block
a=int(input("enter a")) b=int(input("enter b")) try: c=a/b print("a/b=%d" %c) except: print("can't divide with zero") else: print("this is else block")
Output: enter a4 enter b3 a/b=1 this is else block
Finally block:
Finally block will be executed regardless if the try block raises an error or not
a=int(input("enter a")) b=int(input("enter b")) try: c=a/b print("a/b=%d" %c) except: print("can't divide with zero") else: print("this is else block") finally: print("thankyou")
Output: enter a4 enter b3 a/b=1 this is else block thankyou === Code Execution Successful ===