The Wayback Machine - https://web.archive.org/web/20240927070346/https://www.geeksforgeeks.org/python-try-except/
Open In App

Python Try Except

Last Updated : 26 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 
 

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)

Auxiliary Space: O(1)

Output : 
 

Yeah ! Your answer is : 1


Code 1: 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)

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.

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) 

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: 
 

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)


Previous Article
Next Article

Similar Reads

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
6 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
Flow control in try catch finally in Java
In this article, we'll explore all the possible combinations of try-catch-finally which may happen whenever an exception is raised and how the control flow occurs in each of the given cases. Control flow in try-catch clause OR try-catch-finally clause Case 1: Exception occurs in try block and handled in catch blockCase 2: Exception occurs in try-bl
6 min read
Matrix sum except one item
Given N*M matrix find the sum of the elements of the matrix without the element specified by its position Examples: Input : mat[] = {{1 2 4}, {5 6 8}} cell = (0 2) Output :22 We need to find sum of all elements except mat[0][2]. Input : mat[][] = {{5 6 2 3}, {2 3 1 8}, {9 6 5 2}} cell = (1 2) Output :51 Approach 1: A simple solution is to traverse
15 min read
Select all columns, except one given column in a Pandas DataFrame
DataFrame Data structure are the heart of Pandas library. DataFrames are basically two dimension Series object. They have rows and columns with rows representing the index and columns representing the content. Now, let's see how to Select all columns, except one given column in Pandas DataFrame in Python. Creating a DataFrame: C/C++ Code # import p
2 min read
PySpark DataFrame - Select all except one or a set of columns
In this article, we are going to extract all columns except a set of columns or one column from Pyspark dataframe. For this, we will use the select(), drop() functions. But first, let's create Dataframe for demonestration. C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSess
2 min read
Remove character in a String except Alphabet
Given a string consisting of alphabets and other characters, remove all the characters other than alphabets and print the string so formed. Example Input: str = "$Gee*k;s..fo, r'Ge^eks?" Output: GeeksforGeeks Program to Remove characters in a string except alphabetsBelow are the steps and methods by which we can remove all characters other than alp
2 min read
PostgreSQL - EXCEPT Operator
In PostgreSQL, the EXCEPT operator is a powerful tool used to return distinct rows from the first query that are not present in the output of the second query. This operator is useful when you need to compare result sets of two or more queries and find the differences. Let us better understand the EXCEPT Operator in PostgreSQL from this article. Sy
3 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guar
7 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Python Debugger – Python pdb
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules. The major advantage of pdb is it runs purely in the command line
5 min read
Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
2 min read
Python: Iterating With Python Lambda
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the expressionexpression can be an mathematical expressio
2 min read
Python Value Error :Math Domain Error in Python
Errors are the problems in a program due to which the program will stop the execution. One of the errors is 'ValueError: math domain error' in Python. In this article, you will learn why this error occurs and how to fix it with examples. What is 'ValueError: math domain error' in Python?In mathematics, we have certain operations that we consider un
4 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and going for walks in Python packages. While there are ma
3 min read
GeeksforGeeks Python Foundation Course - Learn Python in Hindi!
Python - it is not just an ordinary programming language but the doorway or basic prerequisite for getting into numerous tech domains including web development, machine learning, data science, and several others. Though there's no doubt that the alternatives of Python in each of these respective areas are available - but the dominance and popularit
5 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
Python Image Editor Using Python
You can create a simple image editor using Python by using libraries like Pillow(PIL) which will provide a wide range of image-processing capabilities. In this article, we will learn How to create a simple image editor that can perform various operations like opening an image, resizing it, blurring the image, flipping and rotating the image, and so
13 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
5 min read
Learn DSA with Python | Python Data Structures and Algorithms
This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with th
15+ min read
Why we write #!/usr/bin/env python on the first line of a Python script?
The shebang line or hashbang line is recognized as the line #!/usr/bin/env python. This helps to point out the location of the interpreter intended for executing a script, especially in Unix-like operating systems. For example, Linux and macOS are Unix-like operating systems whose executable files normally start with a shebang followed by a path to
2 min read
Setting up ROS with Python 3 and Python OpenCV
Setting up a Robot Operating System (ROS) with Python 3 and OpenCV can be a powerful combination for robotics development, enabling you to leverage ROS's robotics middleware with the flexibility and ease of Python programming language along with the computer vision capabilities provided by OpenCV. Here's a step-by-step guide to help you set up ROS
3 min read
Article Tags :
Practice Tags :