Python Exceptions Handling

As in the beginning of this tutorial we have studied about the types of errors that occur in a program. Sometimes we what to catch some or all errors that can possibly get generated; and as a programmer, we want to be as specific as possible. So, python allows programmers to deal with errors smoothly.

Exceptions are events that are used to modify the flow of control through a program when the error occurs. Exceptions get triggered automatically on finding errors in Python.

These exceptions are processed using five statements. These are:

  1. try/except: catch the error and recover from exceptions hoist by programmers or Python itself.
  2. try/finally: Whether exception occurs or not, it automatically performs the clean-up action.
  3. assert: triggers an exception conditionally in the code.
  4. raise: manually triggers an exception in the code.
  5. with/as: implement context managers in older versions of Python such as - Python 2.6 & Python 3.0.

The last was an optional extension to Python 2.6 & Python 3.0.

Why are Exceptions Used?

Exceptions allow us to jump out of random illogical large chunks of codes in case of errors. Let us take a scenario that you have given a function to do a specific task. If you go there and found those things missing that are required to do that specific task, what will you do? Either you stop working or think about a solution - where to find those items to perform the task. The same thing happens here in case of Exceptions also. Exceptions allow programmers jump to an exception handler in a single step, abandoning all function calls. You can think exceptions to an optimized quality go-to statement, in which the program error that occurs at runtime gets easily managed by the exception block. When the interpreter encounters an error, it lets the execution go to the exception part to solve and continue the execution instead of stopping.

While dealing with exceptions, the exception handler creates a mark & executes some code. Somewhere further within that program the exception is raised that solves the problem & makes Python jump back to the marked location; by not throwing away/skipping any active functions that were called after the marker was left.

Roles of an Exception Handler in Python

  • Error handling: The exceptions get raised whenever Python detects an error in a program at runtime. As a programmer, if you don't want the default behavior then code a 'try' statement to catch and recover the program from an exception. Python will jump to the 'try' handler when the program detects an error the execution will be resumed.
  • Event Notification: Exceptions are also used to signal suitable conditions & then passing result flags around a program & text them explicitly.
  • Terminate Execution: There may arise some problems or errors in programs that it needs a termination. So try/finally is used that guarantees that closing-time operation will be performed. The 'with' statement offers an alternative for objects that support it.
  • Exotic flow of Control: Programmers can also use exceptions as a basis for implementing unusual control flow. Since there is no 'go to' statement in Python so exceptions can help in this respect.

A Simple Program to Demonstrate Python Exception Handling

Example 01:
(a,b) = (6,0)
try:# simple use of try-except block for handling errors
    g = a/b
except ZeroDivisionError:
    print ("This is a DIVIDED BY ZERO error")
Output:
This is a DIVIDED BY ZERO error

The above program can also be written like this:

Example 02:
(a,b) = (6,0)
try:
    g = a/b
except ZeroDivisionError as s:
    k = s
    print (k)
#Output will be: integer division or modulo by zero
Output:
division by zero

The 'try - Except' Clause with No Exception

The structure of such type of 'except' clause having no exception is shown with an example.

try:
# all operations are done within this block.
. . . . . . 
except:
# this block will get executed if any exception encounters.
. . . . . . 
else:
# this block will get executed if no exception is found.
. . . . . .

All the exceptions get caught where there is try/except the statement of this type. Good programmers use this technique of exception to make the program fully executable.

'except' Clause with Multiple Exceptions

try:
# all operations are done within this block.
. . . . . . 
except ( Exception1 [, Exception2[,….Exception N ] ] ] ) : 
# this block will get executed if any exception encounters from the above lists of exceptions.
. . . . . .
else:
# this block will get executed if no exception is found.
. . . . . .

The 'try - Finally' Clause

try:
# all operations are done within this block.
. . . . . . 
# if any exception encounters, this block may get skipped.
finally: 
 . . . . . .
# this block will definitely be executed.

Courses
Subscribe Updates via Email

Join 49,000+ W3schools lovers and get all the latest tutorials, programs, algorithms in your inbox.