How do you catch one specific exception in Python?

Experience Level: Junior
Tags: Python

Answer

Use try/except block. In the except block define the type of exception that you want to catch.

Example:

def my_method():
    try:
        int("This will cause exception to be raised")
    except Exception:
        print("Something went wrong.")

Python for beginners
Python for beginners

Are you learning Python ? Try our test we designed to help you progress faster.

Test yourself