

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- How do I manually throw/raise an exception in Python?
- How to raise Python exception from a C extension?
- How do I raise an http error/exception from a Python CGI script?
- 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 raise an error within MySQL?
- How to ignore an exception and proceed in Python?
- How to pass a variable to an exception in Python?
- Argument of an Exception in Python
- How to handle an exception in JSP?
- How to rethrow an exception in Java?
- How will you explain that an exception is an object in Python?
- How to get Python exception text?
Advertisements