0% found this document useful (0 votes)
34 views20 pages

Error and Exception Handling

The document discusses error handling and exceptions in Python programs. It explains the different types of errors like syntax errors and logic errors. It then describes what exceptions are and how they can be handled using try, except, and finally blocks. It provides examples of handling multiple exceptions, raising exceptions, and using else and finally clauses.

Uploaded by

gowtham978718
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views20 pages

Error and Exception Handling

The document discusses error handling and exceptions in Python programs. It explains the different types of errors like syntax errors and logic errors. It then describes what exceptions are and how they can be handled using try, except, and finally blocks. It provides examples of handling multiple exceptions, raising exceptions, and using else and finally clauses.

Uploaded by

gowtham978718
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

1

Python Programming
Using Problem Solving Approach

Reema Thareja

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


CHAPTER 8
Error and Exception Handling

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Errors and Exceptions
The programs that we write may behave abnormally or unexpectedly because of some errors and/or
exceptions. The two common types of errors that we very often encounter are syntax errors and logic errors.
While logic errors occur due to poor understanding of problem and its solution, syntax errors, on the other
hand, arises due to poor understanding of the language. However, such errors can be detected by exhaustive
debugging and testing of procedures.
But many a times, we come across some peculiar problems which are often categorized as exceptions.
Exceptions are run-time anomalies or unusual conditions (such as divide by zero, accessing arrays out of its
bounds, running out of memory or disk space, overflow, and underflow) that a program may encounter during
execution. Like errors, exceptions can also be categorized as synchronous and asynchronous exceptions.While
synchronous exceptions (like divide by zero, array index out of bound, etc.) can be controlled by the program,
asynchronous exceptions (like an interrupt from the keyboard, hardware malfunction, or disk failure), on the
3

other hand, are caused by events that are beyond the control of the program.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
Syntax and Logic Errors
Syntax errors occurs when we violate the rules of Python and they are the most common kind of error that we
get while learning a new language. For example, consider the lines of code given below.
>>> i=0
>>> if i == 0 print(i)
SyntaxError: invalid syntax

Logic error specifies all those type of errors in which the program executes but gives incorrect results. Logical
error may occur due to wrong algorithm or logic to solve a particular program. In some cases, logic errors
may lead to divide by zero or accessing an item in a list where the index of the item is outside the bounds of
the list. In this case, the logic error leads to a run-time error that causes the program to terminate abruptly.
These types of run-time errors are known as exceptions. 4

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Exceptions
Even if a statement is syntactically correct, it may still cause an error when executed. Such errors that occur
at run-time (or during execution) are known as exceptions. An exception is an event, which occurs during
the execution of a program and disrupts the normal flow of the program's instructions.When a program
encounters a situation which it cannot deal with, it raises an exception. Therefore, we can say that an
exception is a Python object that represents an error.
When a program raises an exception, it must handle the exception or the program will be immediately
terminated.You can handle exceptions in your programs to end it gracefully, otherwise, if exceptions are not
handled by programs, then error messages are generated..

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Handling Exceptions
We can handle exceptions in our program by using try block and except block. A critical operation which can
raise exception is placed inside the try block and the code that handles exception is written in except block. The
syntax for try–except block can be given as,
Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Multiple Except Blocks
Python allows you to have multiple except blocks for a single try block. The block which matches with
the exception generated will get executed. A try block can be associated with more than one except
block to specify handlers for different exceptions. However, only one handler will be executed. Exception
handlers only handle exceptions that occur in the corresponding try block. We can write our programs
that handle selected exceptions. The syntax for specifying multiple except blocks for a single try block
can be given as, Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Multiple Exceptions in a Single Block — Example

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


except: Block without Exception
You can even specify an except block without mentioning any exception (i.e., except:). This type of except
block if present should be the last one that can serve as a wildcard (when multiple except blocks are
present). But use it with extreme caution, since it may mask a real programming error.
In large software programs, may a times, it is difficult to anticipate all types of possible exceptional
conditions.Therefore, the programmer may not be able to write a different handler (except block) for every
individual type of exception. In such situations, a better idea is to write a handler that would catch all types
of exceptions.The syntax to define a handler that would catch every possible exception from the try block is,

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Except Block Without Exception — Example

10

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


The Else Clause
The try ... except block can optionally have an else clause, which, when present, must follow all except blocks.
The statement(s) in the else block is executed only if the try clause does not raise an exception.
Examples:

11

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Raising Exceptions
You can deliberately raise an exception using the raise keyword.The general syntax for the raise statement is,
raise [Exception [, args [, traceback]]]
Here, Exception is the name of exception to be raised (example, TypeError). args is optional and specifies a
value for the exception argument. If args is not specified, then the exception argument is None.The final
argument, traceback, is also optional and if present, is the traceback object used for the exception.

Example:

12

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Instantiating Exceptions
Python allows programmers to instantiate an exception first before raising it and add any attributes (or
arguments) to it as desired. These attributes can be used to give additional information about the error. To
instantiate the exception, the except block may specify a variable after the exception name. The variable
then becomes an exception instance with the arguments stored in instance.args. The exception instance also
has the __str__() method defined so that the arguments can be printed directly without using instance.args.

Example:

13

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Handling Exceptions In Invoked Functions

Example:

14

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Built-in and User-defined Exceptions

15

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


The finally Block
The try block has another optional block called finally which is used to define clean-up actions that must be
executed under all circumstances.The finally block is always executed before leaving the try block.This means
that the statements written in finally block are executed irrespective of whether an exception has occurred or
not.The syntax of finally block can be given as, Example:
try:
Write your operations here
......................
Due to any exception, operations written here will be skipped
finally:
This would always be executed.
...................... 16

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Pre-defined Clean–up Action
In Python, some objects define standard clean-up actions that are automatically performed when the object
is no longer needed. The default clean-up action is performed irrespective of whether the operation using the
object succeeded or failed.We have already seen such an operation in file handling.We preferred to open
the file using with keyword so that the file is automatically closed when not in use. So, even if we forget to
close the file or the code to close it is skipped because of an exception, the file will still be closed.
Example:

17

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Re-raising Exception
Python allows programmers to re-raise an exception. For example, an exception thrown from the try block
can be handled as well as re-raised in the except block using the keyword raise.The code given below
illustrates this concept.
Example: Program to re-raise the exception

18

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Assertions in Python
An assertion is a basic check that can be turned on or off when the program is being tested.You can think of assert as a
raise-if statement (or a raise-if-not statement). Using the assert statement, an expression is tested, and if the result of the
expression is False then an exception is raised.The assert statement is intended for debugging statements. It can be seen as
an abbreviated notation for a conditional raise statement.
In Python, assertions are implemented using assert keyword. Assertions are usually placed at the start of a function to
check for valid input, and after a function call to check for valid output.
When Python encounters an assert statement, the expression associated with it is calculated and if the
expression is False, an AssertionError is raised.The syntax for assert statement is,
assert expression[, arguments]
If the expression is False (also known as assertion fails), Python uses ArgumentExpression as the argument for the
AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except block.
However, if the AssertionError is not handled by the program, the program will be terminated and an error message will
19
be displayed. In simple words, the assert statement, is semantically equivalent to writing,
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
assert <expression>, <message>
Assertions In Python — Example

20

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

You might also like