Try, Except, else and Finally in Python
Last Updated :
08 Sep, 2024
An Exception is an Unexpected Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which prevents your program from interrupting.
Example: In this code, The system can not divide the number with zero so an exception is raised.
Python
Output
Traceback (most recent call last):
File "/home/8a10be6ca075391a8b174e0987a3e7f5.py", line 3, in <module>
print(a/b)
ZeroDivisionError: division by zero
Exception handling with try, except, else, and finally
- Try: This block will test the excepted error to occur
- Except: Here you can handle the error
- Else: If there is no exception then this block will be executed
- Finally: Finally block always gets executed either exception is generated or not
Python Try, Except, else and Finally Syntax
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Working of 'try' and 'except'
Let’s first understand how the Python try and except works
- First try clause is executed i.e. the code between try and except clause.
- If there is no exception, then only try clause will run, except clause will not get executed.
- 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.
Example: Let us try to take user integer input and throw the exception in except block.
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)
divide(3, 0)
Output:
Yeah ! Your answer is : 1
Sorry ! You are dividing by zero
Catch Multiple Exceptions in Python
Here's an example that demonstrates how to use multiple except clauses to handle different exceptions:
Python
try:
x = int(input("Enter a number: "))
result = 10 / x
except ZeroDivisionError:
print("You cannot divide by zero.")
except ValueError:
print("Invalid input. Please enter a valid number.")
except Exception as e:
print(f"An error occurred: {e}")
Output:
Enter a number: An error occurred: EOF when reading a line
Else Clauses in Python
The code enters the else block only if the try clause does not raise an exception.
Example: Else block will execute only when no exception occurs.
Python
# Python code to illustrate working of try()
def divide(x, y):
try:
# Floor Division : Gives only Fractional
# Part as Answer
result = x // y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Yeah ! Your answer is :", result)
# Look at parameters and note the working of Program
divide(3, 2)
divide(3, 0)
Output:
Yeah ! Your answer is : 1
Sorry ! You are dividing by zero
Python finally Keyword
Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after normal termination of try block or after try block terminates due to some exception. Even if you return in the except block still the finally block will execute
Example: Let's try to throw the exception in except block and Finally will execute either exception will generate or not
Python
# Python code to illustrate
# working of try()
def divide(x, y):
try:
# Floor Division : Gives only Fractional
# Part as Answer
result = x // y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Yeah ! Your answer is :", result)
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
# Look at parameters and note the working of Program
divide(3, 2)
divide(3, 0)
Output:
Yeah ! Your answer is : 1
This is always executed
Sorry ! You are dividing by zero
This is always executed
Similar Reads
Errors and Exceptions in Python Errors are problems in a program that causes the program to stop its execution. On the other hand, exceptions are raised when some internal events change the program's normal flow. Syntax Errors in PythonSyntax error occurs when the code doesn't follow Python's rules, like using incorrect grammar in
3 min read
Concrete Exceptions in Python In Python, exceptions are a way of handling errors that occur during the execution of the program. When an error occurs Python raises an exception that can be caught and handled by the programmer to prevent the program from crashing. In this article, we will see about concrete exceptions in Python i
3 min read
User-defined Exceptions in Python with Examples In Python, exceptions are used to handle errors that occur during the execution of a program. While Python provides many built-in exceptions, sometimes we may need to create our own exceptions to handle specific situations that are unique to application. These are called user-defined exceptions.To m
4 min read
Python Try Except 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 and jumps to exception block. These blocks let you handle the errors without crashing
6 min read
Python Built-in Exceptions In Python, exceptions are events that can alter the flow of control in a program. These errors can arise during program execution and need to be handled appropriately. Python provides a set of built-in exceptions, each meant to signal a particular type of error.We can catch exceptions using try and
8 min read