• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Suppress Exceptions in Python

Suppress Exceptions in Python

Author: Aditya Raj
Last Updated: July 10, 2022

In python, we normally use try-except blocks to handle exceptions in python. What if we don’t want to handle the exceptions?  What if we just want to ignore the exceptions? In this article, we will discuss how we can suppress exceptions in python

Exception Handling in Python

When an exception occurs in a program, the execution of the program is abruptly interrupted. For instance, if we try to divide a number by 0, an exception will occur and the program will give the following trace-back for the exception as shown below.

num1 = 10
num2 = 0
print("The first number is:", num1)
print("The second number is:", num2)
output = num1 / num2
print("The output is:", output)

Output:

The first number is: 10
The second number is: 0
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 5, in <module>
    output = num1 / num2
ZeroDivisionError: division by zero

When a program is stopped abruptly, all the work done by the program will be lost. To make sure that the program executes after saving the work, we normally handle exceptions using python try-except blocks as follows.

try:
    num1 = 10
    num2 = 0
    print("The first number is:", num1)
    print("The second number is:", num2)
    output = num1 / num2
    print("The output is:", output)
except:
    print("Exception occurred.")

Output:

The first number is: 10
The second number is: 0
Exception occurred.

Here, the business logic is written in the try block, and the code to handle exceptions is written in the except block. Now, let’s see how we can suppress an exception using the try-except blocks.

Suppress Exception Using Try-Except in Python

To suppress an exception means that we will not handle the exception explicitly and it shouldn’t cause the program to terminate. Using the try-except blocks and the pass statement in python, we can suppress the exceptions in python. The pass statement is used as a null statement. When executed, it does nothing. 

To suppress the exceptions, we can use the pass in the except block instead of the exception handling code. In this way, the exception will also be handled and no extra work will be done if an exception occurs. You can use the pass statement with try-except blocks to suppress exceptions in python as follows.

try:
    num1 = 10
    num2 = 0
    print("The first number is:", num1)
    print("The second number is:", num2)
    output = num1 / num2
    print("The output is:", output)
except:
    pass

Output:

The first number is: 10
The second number is: 0

Suppress Exception Using the contextlib Module in Python

Instead of using the try-except blocks and the pass statement, we can use the contextlib module to suppress exceptions in python. In this approach, we will create a context with the which statement and the suppress() function by giving the exception as an input argument to the suppress() method.

Whenever an exception will be raised inside the context, it will be automatically suppressed by the python interpreter. You can observe this in the following example.

import contextlib

with contextlib.suppress(Exception):
    num1 = 10
    num2 = 0
    print("The first number is:", num1)
    print("The second number is:", num2)
    output = num1 / num2
    print("The output is:", output)

Output:

The first number is: 10
The second number is: 0

Conclusion

In this article, we have discussed two ways to suppress exceptions in python.  To know more about programming in python, you can read this article on list comprehension in python. You might also like this article on dictionary comprehension in python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us