Skip to content

Python raise exception with custom message | Manually raising

  • by

If you want to set up manually python exception then you can do it in Python. Python raise exception is the settlement to throw a manual error.

It’s always suggestible Don’t raise generic exceptions. Learn about Generic exception must read this tutorial – Python exception Handling | Error Handling

Python raise exception with custom message | Manually raising

Syntax

In Python 3 there are 4 different syntaxes of raising exceptions.

  1. raise exception – No argument print system default message
  2. raise exception (args)– with an argument to be printed
  3. raise – without any arguments re-raises the last exception
  4. raise exception (args) from original_exception – contain the details of the original exception
raise ValueError('I am erorr')

In this tutorial, we used raise exception(args) to raise an exception.  The args will be print by exception object.

Python raises exception Example:

It’s a simple example for raise exceptions with a custom message. The sole argument to raise shows the exception to be raised.

try:
    raise NameError('HiThere')
except NameError:
    print('An raise exception !')
    raise

Output: 

Python raise exception with custom message | Manually raising output

Let’s see Another Example

If you want an throwing error on any condition, like if negative values have entered. So you can do it like that example.

try:
    a = int(input("Enter a positive Number: "))
    if a <= 0:
        raise ValueError("it's not a positive number!")
except ValueError as ve:
    print(ve)

Output: 

example of raise exception Handling output

QA: How to raise an exception in Python 3

it can be your interview question. There is simply you have to write an raise exception(args) in try except block, same as upper examples.

Reference :

Must read this thread on StackOverflow: https://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python

Official Site: https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement

Bonus: this tutorial is not cover the exception and error handling, for that you must follow this tutorial.

Do comment if you have any doubt and suggestion on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All examples are of raise exception in python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

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