Python Exceptions: An exception is an event, which occurs during the execution of the program. Python has many built-in exceptions that force your program to output an error when something in it goes wrong. There three different types of Python exceptions. They are trying, except, finally.
Python Exceptions
try
When an error occurs, or exception as we call it, Python will normally stop and generate an error message. These exceptions can be handled using the try statement.
Syntax
try:
#block of code
except Exception 1:
#block of code
except Exception 2:
#block of code
#other code
Example
try: print(x) except: print ("An exception occurred")
Output
An exception occurred
Since the try block raises an error, the except block will be executed.
except & else
You can use the else keyword to define a block of code to be executed if no errors were raised.
Example
try: print("Hello") except: print ("Something went wrong") else: Print ("Nothing went wrong")
Output
Hello
Nothing went wrong
Finally
Finally, block, if specified, will be executed regardless if the try block raises an error or not.
Example
try: print(x) except: print("Something went wrong") finally: print("The 'try except' is finished")
Output
Something went wrong
The ‘try except’ is finished
Raising Exceptions
In python, exceptions are raised when corresponding error occurs at run time, but we can forcefully raise it during the keyword raise. An exception object is created by raise can contain a message string that provides a meaningful error message. In addition to the string, it is relatively simple to attach additional attributes to the exception.
Syntax: raise Exception_class,<value>
Example:
try:age = int(input("Enter the age?")) if age<18:raise ValueError;else:print("the age is valid") except ValueError:print("The age is not valid")
Output:
Enter the age? 17
The age is not valid
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.
Example
class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg try: raise Networkerror("Bad hostname") except Networkerror,e: print e.args