Exception Handling
Exception Handling
Example:
>>>Print(4+5) #should be print
>>>print "Hello" #( ) missing
Semantic Error:
Semantic refers to the set of rules which give the meaning of a statement, and when the
statements are not meaningful the error is semantic error.
Example: X*Y = Z
Logical and Runtime Error A good program is the one that has a code that handles an exception
Logical Error: well i.e. In case an exception occurs, then the exception handling code
Error occurred due to incorrect logic applied by the programmer. written for it will take over and do the necessary action.
Python runtime errors Each time an error is detected in a program, the Python interpreter
raises (throws) an (specific) exception
• Division by zero error
Exception handlers code (built-in/userdefined) designed for that
• Performing an operation on incompatible types specific exception executes and handles the error generated
• Using an identifier which has not been defined Programmers can also forcefully raise exceptions within a program
• Accessing a list element, dictionary value or object using the raise and assert statements
attribute which doesn’t exist
Once an exception is raised, no further statement in the current block
• Trying to access a file which doesn’t exist of code is executed
Built-in Exceptions
Exceptions
• Commonly occurring exceptions are usually defined in the
compiler/interpreter. These are called built-in exceptions.
An exception is an error that happens while program is running. It • Python’s standard library is an extensive collection of built-in
interrupts the normal flow of program and indicate that something
exceptions that deals with the commonly occurring errors
unusual has happened in the program.
(exceptions) by providing the standardized solutions for such
errors.
Ex. • On the occurrence of any built-in exception, the appropriate
Entering wrong pin in a ATM machine is an error in user input.
“Not enough amount in the account” is an exception exception handler code is executed which displays the reason
Division by zero is an exception along with the raised exception name.
File not found is an exception
• The programmer then has to take appropriate action to
handle it.
Exception Description
It is raised when there is an error in the syntax of
SyntaxError
the Python code.
Exception Description
Raised when a built-in operation or function IndentationError Raised due to incorrect indentation
ValueError receives and argument with inappropriate type e.g.
int("A123")
Exception Description
Raised when an index is not found in a
IndexError
sequence i.e. out of range
NameError Name when an identifier name is not found Exception Description
Raised when a built-in operation or function
IndentationError Raised due to incorrect indentation
ValueError receives and argument with inappropriate
Raised when an operation or function is type e.g. int("A123")
TypeError applied to an object of inappropriate type e.g.
multiplication of two strings
It is raised when the result of a calculation
OverFlowError exceeds the maximum limit for numeric data
type.
Raised when an object does not find an
AttributeError
attribute
Raised when a mapping (dictionary) key is not
KeyError
found in the set of existing keys
Raised when trying to import a module which
ModuleNotFoundError
doesn’t exist
FileNotFoundError
and
UnsupportedOperation
Syntax/parsing error is a type of exception which is generated are sub-class of IOError
when the code is syntactically wrong, all other exception will
generate if the code syntactically correct.
Exception Description Exception Description
Raised when file methods for reading tries
It is raised when the user accidentally hits the Delete or EOFError
to read beyond the file
KeyboardInterrupt Esc key while executing a program due to which the
normal flow of the program is interrupted.
Exception Description
Exception Description Raised when an index is not found in a
IndexError
Raised if the requested element doesn’t sequence i.e. out of range
ImportError
exist in the module
Exception Description
Exception Description Raised when an object does not find an
AttributeError
attribute
NameError Name when an identifier name is not found
Exception Description
OverFlowError
It is raised when the result of a calculation exceeds Raising Exception
the maximum limit for numeric data type.
Apart from built-in exceptions programmers can also
forcefully raise exceptions in a program using the raise
and assert statements
raise statement assert statement
The raise statement can be used to throw an exception. The syntax of An assert statement in Python is used to test an expression in the
raise statement is: program code. If the result after testing comes false, then the exception
is raised.
raise exception-name[(optional argument)]
This statement is generally used in the beginning of the function or
The argument is generally a string that is displayed when the exception is after a function call to check for valid input.
raised, along with a brief description of the error. Ex:
The syntax for assert statement is:
assert Expression[,arguments]
The error detected may be a built-in exception or may be user-defined. It’s a debugging tool used by software developers.
User-defined raise
Bulit-in exception
handled in raise
Handling Exception
The runtime system searches the entire program for a block of code,
Each and every exception has to be handled by the programmer called the exception handler that can handle the raised exception.
to avoid the program from crashing abruptly.
It first searches for the method in which the error has occurred and
This is done by writing additional code in a program to give the exception has been raised.
proper messages or instructions to the user on encountering an
exception. This process is known as exception handling. If not found, then it searches the method from which this method
(in which exception was raised) was called.
It’s a technique to capture runtime errors and handling them so
as to avoid the program getting crashed. This hierarchical search in reverse order continues till the exception
handler is found. This entire list of methods is known as call stack.
The object is handed over to the runtime system so that it can find an
appropriate code to handle this particular exception.
Imp: During program execution when an exception occurs the control jumps to the exception
handler, abandoning execution of the remaining program statements.
Sometimes, a single piece of code might be suspected to have more
Catching Exceptions than one type of error. For handling such situations, we can have
multiple except blocks for a single try block.
An exception is said to be caught when a code that is designed
to handle a particular exception is executed. When an exception is raised, a search for the matching except block is
made till it is handled. If no match is found, then the program
terminates.
Syntax:
try: With print(A+B+C)
code that may generate exception
except:
code to handle the exception
Without
print(A+B+C)
But if there is no error then none of the except blocks will be executed.
In this case, the statements inside the else clause will be executed.
Finally Clause
The try statement in Python can also have an optional finally clause.
If used, finally should always be placed at the end of try clause, after
all except blocks and the else block.
Alternative Code
Recovering and continuing with finally clause To summarise,
Put the piece of code where there are possibilities of errors or
If an error has been detected and is not handled by any of the exceptions to occur inside a try block.
except clauses, then it is re-raised after the execution of the finally
block. Inside each except clause, define handler codes to handle the
matching exception raised in the try block.
Unlike except, execution of the finally clause does not terminate the
exception. Rather, the exception continues to be raised after The optional else clause contains codes to be executed if no exception
execution of finally. occurs.