Introduction
In Python, the try and except statement is used to catch and handle exceptions. Before knowing more about try and except in Python, let us understand what the exception is?
In Python, an exception is a Python object that represents an error. Python provides many built-in exceptions that are raised when our program encounters an error. When these exceptions occur, the Python interpreter suspends the current process and passes control to the calling process until the problem is resolved. The program will crash if it is not handled properly.
Here is a list of common exceptions that a standard Python program can throw.
- ZeroDivisionError: It occurs when a number is divided by zero.
- ValueError: Occurs when the built-in function receives a wrong argument.
- IndentationError: It occurs if an incorrect indentation is given.
- EOFError: It occurs when End-Of-File is hit without reading any data.
- IOError: It occurs when the file can not be opened.
- ImportError: It occurs when the module is not found.
Recommended Topic, Floor Division in Python and Convert String to List Python.
Try and Except in Python
If a python program contains suspicious code that may throw the exception, we must use the Try and Except statements to handle this exception. We use the try block to check for errors in code. The code inside the try block will run if the program contains no errors. On the other hand, the code in the except block will run whenever the program encounters an error in the try block before it.
Read More, leap year program in python
Syntax
try:
# Block of code
except:
# Executed if an error in the try block
Let us look at how the different blocks in the above syntax work.
- The try clause, the code between the try and except clauses, is first executed.
- Only the try clause will be executed if there is no exception, except clause is skipped.
- If an exception occurs, the try clause is skipped, and the except clause is executed instead.
- There can be several except clauses in a try statement.
Example 1
def division(a,b):
try:
res=a//b
print("The answer is :", res)
except ZeroDivisionError:
print("Can not divide with zero")
division(14,3)
Output
The answer is : 4
In the above code, there is no exception, so the try clause will run.
Example 2
def division(a,b):
try:
res=a//b
print("The answer is :", res)
except ZeroDivisionError:
print("Can not divide with zero")
division(14,0)
Output
Can not divide with zero
In the above code, there is an exception, so only except clause will run.
Recommended Topic, Divmod in Python