Python Exception Handling
Exceptions are the events which can change the flow of control through a program. In Python, exceptions can be both intercepted and triggered by our programs. They are processed by two new statements:-
- Try – Catches exceptions raised by Python or a program
- Raise – Triggers an exception manually
In typical Python programs, exceptions may be used for a variety of things:
- Error handling
- Event notification
- Special-case handling
- Unusual control-flows
These exceptions are the high-level control flow device. They exceptions may be raised either by python or by our programs. In these both cases try statement is used. Python try statements come in two types –
- One that handles exceptions
- Other that executes finalization code whether exceptions occur or not.
It initiate with a try header line which is followed by a block of indented statements then one or more optional except clauses and then at the end an optional else clause like as follows:
try: <statements> # run/call actions except <name>: <statements> # if 'name' raised during try block except <name>, <data>: <statements> # if 'name' raised; get extra data else: <statements> # if no exception was raised
- If an exception is occurred when the try block’s statements are running then python go back to the try block and runs those statements which comes under the first except clause and that matches the raised exception. Control continues past the entire try statement after the except block runs unless the except block raises another exception.
- If an exception happens in the try block and no except clause is matched then exception is propagated up to a try or to the top level of the process.
- When the statements under the try header run and no exception occurs then python runs the statement which comes under the else and then control is resumed past the whole try statement.
When a finally clause is used in a try then its block of statements is always run by Python whether an exception occurred while the try block was running or not:
- If no exception occurs, Python runs the try block, then the finally block and then continues execution past the entire try statement.
- If an exception does occur during the try block’s run, Python comes back and runs the finally block, but then propagates the exception to a higher try (or the top level); control doesn’t continue past the try statement.
try: <statements> finally: <statements> # always run “on the way out”
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. If extra data is passed then it can be caught in a try by listing an assignment target to receive it: except name, data:
raise <name> # manually trigger an exception raise <name>, <data> # pass extra data to catcher too
def intellipaat(list, n): print list[n] # trigger IndexError try: intellipaat([0, 1, 2], 3) except IndexError: # catch exception here print "Hello world!"
Exception Catching Modes
- try Statement Clauses
When you write try statements, a number of clauses can appear after try statement block.
Table: try Statement Clause Forms
|except:||Catch all (other) exception types|
|except name:||Catch a specific exception only|
|except name, value:||Catch exception and its extra data|
|except (name1, name2):||Catch any of the listed exceptions|
|else:||Run block if no exceptions raised|
|finally:||Always perform block|
- Catching 1-of-N Exceptions
When an exception is raised as the call to the action function is running then python returns to the try and finds for the first except that catches the exception raised. It checks except clauses from top to bottom and left to right and runs the statements under the first that matches. If no matches is found then the exception is propagated past this try; the else runs only when no exception occurred.
try: action() except NameError: … except IndexError … except KeyError: … except (AttributeError, TypeError, SyntaxError): … else: …
User Defined Functions
It is also known as custom exception. Python provides the facility to create your own exceptions class form the built in exceptions.
class userexecption(Exception): def __init__(self, value): self.value = value try: raise userexecption("Error is occured") except userexception,u: print u.value
Error is occurred
This blog will help you get a better understanding of Automate Your Coding with Python!