Open In App

Python Try Except

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.
Note: For more information, refer to Errors and Exceptions in Python
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

 

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

Code 1: No exception, so the try clause will run. 
 

Python3




# 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)


Auxiliary Space: O(1)

Output : 
 

Yeah ! Your answer is : 1

Code 1: There is an exception so only except clause will run. 
 

Python3




# 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)


Output : 
 

Sorry ! You are dividing by zero

 Code 2:  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.

Python3




# 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)


Output:

The 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

Code:

Python3




# 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)

Code:

Python3




# 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'


Output:

Can't divide by zero
This is always executed

Related Articles: 
 

 



Previous Article
Next Article

Similar Reads

try-except vs If in Python
Python is a widely used general-purpose, high level programming language. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently.Most of the people don’t know that Try-Ex
3 min read
Try, Except, else and Finally in Python
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 ex
4 min read
Connectionerror - Try: Except Does Not Work" in Python
Python, a versatile and powerful programming language, is widely used for developing applications ranging from web development to data analysis. However, developers often encounter challenges, one of which is the "ConnectionError - Try: Except Does Not Work." This error can be frustrating as it hinders the robustness of your code, especially when d
4 min read
Python Program to Removes Every Element From A String List Except For a Specified letter
Given a List that contains only string elements, the following program shows methods of how every other alphabet can be removed from elements except for a specific one and then returns the output. Input : test_list = ["google", "is", "good", "goggled", "god"], K = 'g' Output : ['gg', '', 'g', 'ggg', 'g'] Explanation : All characters other than "g"
4 min read
Python | Remove all characters except letters and numbers
Given a string, the task is to remove all the characters except numbers and alphabets. String manipulation is a very important task in a day to day coding and web development. Most of the requests and responses in HTTP queries are in the form of Python strings with sometimes some useless data which we need to remove. Remove all characters except le
4 min read
Python - Generate random number except K in list
Sometimes, while working with python, we can have a problem in which we need to generate random number. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random number from a list except K. Lets discuss certain ways in which this task can be performed. Method #1: Using choice() + list comprehen
3 min read
Python | Generate random number except K in list
Sometimes, while working with Python, we can have a problem in which we need to generate random numbers. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random numbers from a list except K. Let's discuss certain ways in which this task can be performed. Method #1 : Using choice() + list compr
6 min read
Python | Extract characters except of K string
Sometimes, while working with Python strings, we can have a problem in which we require to extract all the elements of string except those which present in a substring. This is quite common problem and has application in many domains including those of day-day and competitive programming. Lets discuss certain ways in which this task can be performe
6 min read
Python program to Replace all Characters of a List Except the given character
Given a List. The task is to replace all the characters of the list with N except the given character. Input : test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'], repl_chr = '*', ret_chr = 'G' Output : ['G', '*', 'G', '*', '*', '*', '*', '*', '*'] Explanation : All characters except G replaced by * Input : test_list = ['G', 'F', 'G', 'B', 'E
4 min read
Python - Reverse String except punctuations
Given a string with punctuations, perform string reverse, leaving punctuations at their places. Input : test_str = 'geeks@#for&%%gee)ks' Output : skeeg@#rof&%%ske)eg Explanation : Whole string is reversed, except the punctuations. Input : test_str = 'geeks@#for&%%gee)ks' [ only substring reversal ] Output : skeeg@#rof&%%eeg)sk Expla
6 min read
Article Tags :
Practice Tags :