How to instantiate exceptions in Python

In this following tutorial, let us look at how to instantiate an exception that is generated using Python.

Many times, even when a statement is syntactically correct, it might cause an error while executing the same. Errors that occur during the execution of a program are called exceptions.

In this tutorial, we will see how to overcome such exceptions by instantiating them.

Also, read:

Exception:

An exception in python is the errors and anomaly that might occur in a user program. To handle this kind of errors we have Exception handling in Python. Exception handling is a method of handling the errors that the user might predict may occur in his/her program. This is why in Python we have the try and catch block for our convenience.

In Python whenever we come across an error, they can be resolved by raising an exception. This can be done by instantiating the error that occurs.

The general syntax being,

  • raise the exception that might occur in try block.
  • then except the exception that occurs with a variable.

The exception instance also has the str () method defined so that the arguments can be printed directly without saving using instance.

Here is the code for the same:

try:
    raise Exception('Hello','World')
except Exception as errorObj:
    print(type(errorObj)) # the exception instance
    print(errorObj.args)  # arguments stored in .args
    print(errorObj)       #__str__ allows args to be printed directly
    arg1,arg2=errorObj.args
    print('Argument1=',arg1)
    print('Argument2=',arg2

OUTPUT:
<type  'exceptions.Exception'>
('Hello', 'World')
('Hello', 'World')
Argument1= Hello
Argument2= World

In the above example, we are first raising an exception in the try block.

When the exception is raised, we are printing the type of error and the arguments directly by using  .args . Then, the arguments are split into arg1 and arg2 and then the corresponding output is printed.

Leave a Reply

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