- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Raising an Exceptions in Python
You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows.
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception.
An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows −
def functionName( level ): if level < 1: raise "Invalid level!", level # The code below to this would not be executed # if we raise the exception
Note − In order to catch an exception, an "except" clause must refer to the same exception thrown either class object or simple string. For example, to capture above exception, we must write the except clause as follows −
try: Business Logic here... except "Invalid level!": Exception handling here... else: Rest of the code here...
- Concrete Exceptions in Python
- User-Defined Exceptions in Python
- Are Python Exceptions runtime errors?
- User-defined Exceptions in Python with Examples
- How do you properly ignore Exceptions in Python?
- How to declare custom exceptions in modern Python?
- Chained Exceptions in C#
- Custom exceptions in Java
- Netflix original Sacred Games is raising controversies all over !!
- PHP Extending Exceptions
- PHP Throwing Exceptions
- Suggest a cleaner way to handle Python exceptions?
- Built-in Exceptions in Java
- Built-in Exceptions in C#
- Describe some of the exceptions available in Selenium with python?