How try() works?
- Try block: Executes the code that might raise an exception.
- Except block: Catches and handles the specific exception if it occurs.
- If no exception occurs, the except block is skipped.
- You can specify multiple exception types or use a general exception handler.
Try and Except Statement – Catching Exceptions
In Python, exceptions are caught and handled using try and except statements. The try clause contains statements that can raise exceptions, whereas the except clause contains statements that handle the exception.
try:
#program code
except:
#exception handling code
#program code
The program flow enters the "try" block.
Control is passed to the code in the "except" block if an exception occurs. The error handling code in the "except" block is determined by the sort of error you expect the code in the "try" block may encounter.
Example
Python
arr = [1, 2, 3, 4, 5]
try:
print ("Third element in the array = %d" %(arr[2]))
print ("Sixth element in the array = %d" %(arr[5]))
except:
print ("Some error occurred")

You can also try this code with Online Python Compiler
Run Code
Output
Third element in the array = 3
Some error occurred
In the example above, the statements that potentially produce an error are placed inside the try statement (second print statement in our case). The second print statement attempts to access the array's sixth element, which is not there, resulting in an exception. The except statement then catches this exception.
Catching Specific Exception
There can be more than one except clause in a try statement to provide handlers for distinct exceptions. Please keep in mind that only one handler will be used.
The common syntax for adding specific exceptions is
try:
# statement(s)
except:
# statement(s)
except:
# statement(s)
Example
Example to handle multiple errors with one except handler
Python
def func(num1):
if num1 < 4:
num2 = num1/(num1-3)
print("Value of num2 = ", num2)
try:
func(3)
except:
print("ZeroDivisionError Occurred and Handled")
try:
func(5)
except:
print("NameError Occurred and Handled")

You can also try this code with Online Python Compiler
Run Code
Output
ZeroDivisionError Occurred and Handled
NameError Occurred and Handled
This happens because when python tries to access the value of num2, NumError occurs.
Try with Else Clause
In some cases, you may wish to run a specific block of code if the code block inside try ran without problems. You can use the optional else keyword with the try statement in these situations.
The else clause must be present after all the except clauses.
If the try clause does not throw an exception, the code moves to the else block.
Example
Python
# program to print the reciprocal of odd numbers
try:
a = int(input("Enter a number: "))
assert a % 2 != 0
except:
print("Even number!")
else:
reciprocal = 1/a
print(reciprocal)

You can also try this code with Online Python Compiler
Run Code
Output
Enter a number: 2
Even number!
Enter a number: 5
0.2
You can try it on online python compiler.
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)

You can also try this code with Online Python Compiler
Run CodeOutput
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)

You can also try this code with Online Python Compiler
Run CodeOutput
Can not divide with zero
In the above code, there is an exception, so only except clause will run.
Finally Keyword in Python
The statement 'finally' is available in Python, and it is always executed after the try and except blocks. The final block is always executed after the try block has terminated normally or due to some exceptions.
Syntax
try:
# Block of code
except:
# Executed if an error in the try block
else:
# Executes if no exception
finally:
# block of code
# this will always be executed
Example
def division(a,b):
try:
res=a//b
print("The answer is:", res)
except ZeroDivisionError:
print("Can not divide with zero")
finally:
print('This is always executed')
division(14,0)

You can also try this code with Online Python Compiler
Run CodeOutput
Can not divide with zero
This is always executed
Raising Exception
The raise statement enables the programmer to compel the occurrence of a specified exception. The exception to be raised is indicated by the sole argument in raise. This must be either an exception instance or a class of exceptions (a class that derives from Exception).
Python
try:
raise NameError("Hi peeps!!")
except NameError:
print ("Exception occurred")
raise # To determine whether the exception was raised or not

You can also try this code with Online Python Compiler
Run Code
Output
File "main.py", line 2, in <module>
raise NameError("Hi peeps!!")
NameError: Hi peeps!!
You can try it on online python compiler.
Frequently Asked Questions
When should we use try/except Python?
When we have a code block to execute that will run correctly sometimes and incorrectly other times, depending on conditions we can't predict when writing the code, we should use try/except Python.
Can we use try without Except?
We can't have a try block without an except block, so the only thing is to try to ignore the raised exception and specify the pass statement in the except block.
Is if-else faster than try-except?
The exception handler ( try/except) is comparatively faster than the explicit if condition until it met with an exception. That means that if an exception is thrown, the exception handler will take longer than if version of the code.
Conclusion
In this article, we have extensively discussed try and except in the Python programming language. We also discussed the syntax and example of the try and except statement in Python.
Recommended Readings: