Skip to content

Python throw exception

  • by

You use the “raise” keyword to throw a Python exception manually. You can add a message to describe the exception type or reason.

Be specific in your message, e.g.:

raise ValueError('A very specific bad thing happened.')

Note: Avoid raising a generic Exception. To catch it, you’ll have to catch all other more specific exceptions that subclass it.

Python throw exception

A simple example is a code checking a condition and raising the exception, if the condition is True raise the exception to warn the user or the calling application.

def demo_bad_catch():
        raise ValueError('Represents a hidden bug, do not catch this')
        raise Exception('This is the exception you expect to handle')
    except Exception as error:
        print('Caught this error: ' + repr(error))



Python throw exception

And more specific catches won’t catch the general exception:

def demo_no_catch():
        raise Exception('general exceptions not caught by specific handling')
    except ValueError as e:
        print('we will not catch exception: Exception')



How to raise an exception in a try-except-else statement?

Answer: try Python assert keyword with an error message.

import logging
for i in range(5):
        assert(1 == i)
        print("try", i)
    except Exception:
        assert(1 == 1)
        print("else", i)
        print("finally", i, "\n")

In Python 3 there are four different syntaxes for raising exceptions:

  1. raise exception
  2. raise exception (args)
  3. raise
  4. raise exception (args) from original_exception

Do comment if you have any doubts or suggestions on this Python exception-handling topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *