Syntax of Try Except in Python
try:
# code that may cause an exception
except ExceptionType:
# code to handle the exception
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.
Finally Keyword in Python
Finally is a keyword in python, which is always run after the try and except blocks. The finally block is always executed after the try block has terminated normally or after the try block has terminated due to an exception.
Syntax
try:
# Some Code
except:
# optional block
# Handling of exception (if required)
else:
# executes if there is no exception
finally:
# Some code(always executed)
Example
Python
try:
e = 5//0
print(e)
except:
print("Can't divide by zero")
finally:
print('This statement is always executed')
You can also try this code with Online Python Compiler
Run Code
Output
Can't divide by zero
This statement 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!!
Must Read, python packages
Frequently Asked Questions
What does it mean to catch an exception Python?
In Python, the try and except block captures and handles errors. As previously demonstrated, when syntactically valid code encounters an issue, Python will throw an exception error. If this exception error is not handled, the application will crash. The except clause specifies how your program handles exceptions.
What happens if the try-catch block is not used?
If no exception occurs in the try block, the catch blocks are ignored.
Can I use try without except in Python?
No, you cannot use try without except. However, you can pair try with finally, which ensures that the final block of code is executed regardless of an exception being raised.
What is finally in try-except Python?
The finally block in Python's try-except structure is used to define code that will run no matter what—whether an exception occurs or not. It’s typically used for cleanup actions like closing files or releasing resources.
What is TypeError in try-except in Python?
A TypeError occurs when an operation is performed on an inappropriate data type. In a try-except block, you can catch and handle this specific error to prevent your program from crashing when the wrong type is used.
Conclusion
In this article, we discussed about try-except in Python. The `try-except` mechanism in Python is an essential tool for robust error handling, allowing programs to gracefully manage exceptions and continue execution. By catching specific errors like `TypeError` or using `finally` for cleanup, developers can write cleaner, more reliable code.
Check out this article - Quicksort Python
Check out the Top 100 SQL Problems to get hands-on experience with frequently asked interview questions and land your dream job.