0% found this document useful (0 votes)
3 views

Exception Handling

Uploaded by

Pankaj Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Exception Handling

Uploaded by

Pankaj Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Python Programming

Error and Exception Handling

1
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
2

other hand, are caused by events that are beyond the control of the program. .
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. 3

.
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..

.
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:

.
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:

.
Multiple Exceptions in a Single Block — Example

.
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,

.
Except Block Without Exception — Example

.
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:

10

.
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:

11

.
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:

12

.
Handling Exceptions In Invoked Functions

Example:

13

.
Built-in and User-defined Exceptions

14

.
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.
...................... 15

.
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

16

.
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
17
be displayed. In simple words, the assert statement, is semantically equivalent to writing,
.
assert <expression>, <message>
Assertions In Python — Example

18

You might also like