
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to raise an exception in Python?
We can force raise an exception using the raise keyword. Here is the syntax for calling the “raise” method.
raise [Exception [, args [, traceback]]]
where, the Exception is the name of the exception; the optional “args” represents the value of the exception argument.
The also optional argument, traceback, is the traceback object used for the exception.
#raise_error.py try: i = int ( input ( "Enter a positive integer value: " ) ) if i <= 0: raise ValueError ( "This is not a positive number!!" ) except ValueError as e: print(e)
If we execute the above script at terminal as follows
$python raise_error.py Enter a positive integer: –6
Following is displayed since we have entered a negative number:
This is not a positive number!!
Alternate example code
# Here there is no variable or argument passed with the raised exception import sys try: i = int ( input("Enter a positive integer value: ")) if i <= 0: raise ValueError#("This is not a positive number!!") except ValueError as e: print sys.exc_info()
output
Enter a positive integer value: -9 (<type 'exceptions.ValueError'>, ValueError(), <traceback object at 0x0000000003584EC8>)
- Related Articles
- How do I manually throw/raise an exception in Python?
- How to raise Python exception from a C extension?
- How to raise an exception in one except block and catch it in a later except block in Python?
- How to handle an exception in Python?
- Where's the standard python exception list for programmers to raise?
- How to pass argument to an Exception in Python?
- How to ignore an exception and proceed in Python?
- How to pass a variable to an exception in Python?
- How to raise an error within MySQL?
- Argument of an Exception in Python
- How to handle an exception in JSP?
- How to catch KeyError Exception in Python?
- How to catch IOError Exception in Python?
- How to catch ArithmeticError Exception in Python?
- How to catch OverflowError Exception in Python?

Advertisements