Exception handling in pyhton:An exception is an error that happens during execution of a program. When thaterror occurs, Python generate an exception that can be handled, which avoids your
program to crash.
why we use excepitons:Exceptions are convenient in many ways for handling errors and special conditionsin a program. When you think that you have a code which can produce an error then you can use exception handling.
Raising an Exception :You can raise an exception in your own program by using the raise exception statement.Raising an exception breaks current code execution and returns the exception back until it is handled.
In Python programming, exceptions are raised when corresponding errors occur at run time, but we can forcefully raise it using the keyword raise.
Catching Exceptions in Python:
Exception are handled by using try and except keyword.A critical operation which can raise exception is placed inside the try clause and the code that handles exception is written in except clause.A try clause can have any number of except clause to handle them differently but only one will be executed in case an exception occurs.
Ex: try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
except:
# handle all other exceptions
pass
How To Raise An Exception And Provide Arguments?
We can forcefully raise an exception using the raise keyword. We can also optionally pass values to the exception and specify why this exception should occur. Here is the syntax for calling the “raise” method.
syntax:raise [Exception [, args [, traceback]]]
i)The exception is the name of the exception.
ii)The “args” is optional and represents the value of the exception argument.
iii)The final argument, traceback, is also optional and if present, is the traceback object used for the exception.
To trigger exceptions you need to code raise statements. Their general form is simple: the keyword raise followed by the name of the exception to be raised. You can also pass an extra data item (an object) along with the exception by listing it after the exception name.
Thank you for sharing wonderful information with us to get some idea about that content.
ReplyDeletePython Online Course
Python Online Training in India