In Python, errors and exceptions can interrupt the execution of program. Python provides try and except blocks to handle situations like this. In case an error occurs in try-block, Python stops executing try block adn jumps to exception block. These blocks let you handle the errors without crashing the program.
Python
try:
# Code that may raise an exception
x = 3 / 0
print(x)
except:
# exception occurs, if code under try throws error
print("An exception occurred.")
OutputAn exception occurred.
Try Except in Python
Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block.
Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
How try() works?
- First, the try clause is executed i.e. the code between try.
- If there is no exception, then only the try clause will run, except clause is finished.
- If any exception occurs, the try clause will be skipped and except clause will run.
- If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops.
- A try statement can have more than one except clause
Some of the common Exception Errors are :
- IOError: if the file can’t be opened
- KeyboardInterrupt: when an unrequired key is pressed by the user
- ValueError: when the built-in function receives a wrong argument
- EOFError: if End-Of-File is hit without reading any data
- ImportError: if it is unable to find the module
Example #1: No exception, so the try clause will run.
Python
# Python code to illustrate
# working of try()
def divide(x, y):
try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
# Look at parameters and note the working of Program
divide(3, 2)
OutputYeah ! Your answer is : 1
Example #2: There is an exception so only except clause will run.
Python
# Python code to illustrate
# working of try()
def divide(x, y):
try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
# Look at parameters and note the working of Program
divide(3, 0)
OutputSorry ! You are dividing by zero
Example #3: The other way of writing except statement, is shown below and in this way, it only accepts exceptions that you’re meant to catch or you can check which error is occurring.
Python
# code
def divide(x, y):
try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
print("Yeah ! Your answer is :", result)
except Exception as e:
# By this way we can know about the type of error occurring
print("The error is: ",e)
divide(3, "GFG")
divide(3,0)
OutputThe error is: unsupported operand type(s) for //: 'int' and 'str'
The error is: integer division or modulo by zero
Else Clause
In Python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception.
Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
Example:
Python
# Program to depict else clause with try-except
# Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) // (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Output-5.0
a/b result in 0
Finally Keyword in Python
Python provides a keyword finally, which is always executed after the try and except blocks. The final block always executes after the normal termination of the try block or after the try block terminates due to some exceptions.
Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
finally:
# Some code .....(always executed)
Python
# Python program to demonstrate finally
# No exception Exception raised in try block
try:
k = 5//0 # raises divide by zero exception.
print(k)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
OutputCan't divide by zero
This is always executed
Related Articles:
Python Try Except – FAQs
What are the common exceptions in Python and how to catch them?
Common exceptions in Python include:
ZeroDivisionError: Raised when dividing by zero.FileNotFoundError: Raised when a file or directory is requested but cannot be found.ValueError: Raised when an operation receives an argument of the correct type but inappropriate value.IndexError: Raised when a sequence subscript is out of range.KeyError: Raised when a dictionary key is not found.
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Can I use try without except in Python?
Yes, but it is less common. A try block can be used without an except block if you include a finally block, which is always executed after the try block, whether an exception was raised or not.
Example:
try:
print("Trying something")
finally:
print("This will always execute")
How to use the finally clause in Python exception handling?
The finally block is used for code that must be executed regardless of whether an exception was raised or not. This is typically used for cleanup actions.
Example:
try:
file = open("example.txt", "r")
# Perform file operations
finally:
file.close() # Ensure file is closed
Can multiple exceptions be handled using a single except clause?
Yes, you can handle multiple exceptions using a single except clause by specifying a tuple of exceptions.
Example:
try:
value = int("string")
except (ValueError, TypeError):
print("Caught a ValueError or TypeError!")
How to create custom exceptions in Python?
You can create custom exceptions by subclassing the built-in Exception class or one of its subclasses.
Example:
class CustomError(Exception):
"""Base class for other exceptions"""
pass
class SpecificError(CustomError):
"""Raised for specific reasons"""
def __init__(self, message):
self.message = message
super().__init__(self.message)
# Raising a custom exception
try:
raise SpecificError("This is a specific error message")
except SpecificError as e:
print(e)