Exception Handling
Exception Handling
TYPESOF ERRORS
SYNTAX ERROR
LOGICAL ERRORS
RUN-TIME ERRORS
SYNTAX ERROR
Syntax errors are detected when we have not followed the rules of the particular programming language while
writing a program.
These errors are also known as parsing errors.
The interpreter does not execute the program unless we rectify the errors, save and rerun the program.
Example:
In shell mode, Python displays the name of the error and a small description about the error.
Example:
LOGICAL ERRORS
Logical errors will produce incorrect results.
These errors will not stop a program from running/executing.
Example: To find perimeter of a rectangle.
L=4,b=6
Perimeter=2 * L + b
Perimeter=2*4 + 6 Result=14
But, it’s a wrong answer.
Exact logical statement to find perimeter of a rectangle is Perimeter = 2 *( L + b )
2*(4+6) Result= 20
RUN-TIME ERRORS
Run-time occurs during a program’s execution.
Run-time errors are also known as Exceptions.
Example: A number divide by zero results in runtime error.
C=3/0
EXCEPTIONS
An exception is a Python object that represents an error.
When an error occurs during the execution of a program, an
exception is raised.
Exception needs to be handled by the programmer so that the program does not terminate abnormally.
Therefore, while designing a program, a programmer may anticipate such erroneous situations that may arise during its
execution and can address them by including appropriate code to handle that exception.
A Programmer can also create custom exceptions to suit one’s
requirements called user defined exceptions.
BUILT-IN FUNCTIONS
Commonly occurring exceptions are usually defined in the compiler/interpreter.
These are called built-in exceptions that provides the standardized solutions for such errors.
The appropriate exception handler code is executed which displays the reason along with the raised exception name. The
programmer then has to take appropriate action to handle it
ExampleofBuilt-in Functions:
\
RAISING EXCEPTIONS
Exception handlers are designed to execute when a specific
exception is raised.
Programmers can also forcefully raise exceptions in a program
using the raise and assert statements.
Once an exception is raised, no further statement in the current block of code is executed. So, raising an exception involves
interrupting the normal flow execution of program and jumping to that part of the program (exception handler code) which is
written to handle such exceptional situations
In Figure, since the value of variable length is greater than the length
of the list numbers, an IndexError exception will be raised.
The statement following the raise statement will not be executed. So, the message “NO EXECUTION” will not be displayed in this case.
The assert Statement
An assert statement in Python is used to test an expression in the program code.
If the result after testing comes false, then the exception is raised.
This statement is generally used in the beginning of the function or after a function call to check for valid input.
The syntax for assert statement is:
assert Expression[,arguments]
On encountering an assert statement, Python evaluates the expression given immediately after the assert keyword.
If this expression is false, an Assertion Error exception is raised which can be handled like any other exception.
In the code, the assert statement checks for the value of the variable number. In case the number gets a negative value,
AssertionError will be thrown, and subsequent statements will not be executed.
Hence, on passing a negative value (-350) as an argument, it results in
AssertionError and displays the message “OOPS…. Negative Number”.
Handling Exceptions
Each and every exception has to be handled by the programmer to avoid the program from crashing abruptly.
This is done by writing additional code in a program to give proper messages or instructions to the user on encountering an
exception. This process is known as exception handling.
Catching Exceptions
An exception is said to be caught when a code that is designed to handle a particular exception is executed.
Exceptions, if any, are caught in the try block and handled in the except block.
While writing or debugging a program, a user might doubt an exception to occur in a particular part of the code.
Such suspicious lines of codes are put inside a try block.
Every try block is followed by an except block.
The appropriate code to handle each of the possible exceptions (in the code inside the try block) are written inside the except
clause.
While executing the program, if an exception is encountered, further execution of the code inside the try block is stopped and the
control is transferred to the except block.
The syntax of try … except clause is as follows:
try:
[program statements where exceptions might occur] except [exception-name]:
[code for exception handling if the exception-name error is encountered]
Program:Usingtry..exceptblock
print ("Practicing for try block") try:
numerator=50
denom=int(input("Enter the denominator: ")) quotient=(numerator/denom)
print(quotient)
print ("Division performed successfully") except ZeroDivisionError:
print ("Denominator as ZERO.... not allowed")
print(“OUTSIDE try..except block”)
In this Program, the ZeroDivisionError exception is handled.
Sometimes, a single piece of code might be suspected to have more than one type of error.
For such situations , we can have multiple except blocks for a single try block
Program: Use of multiple exceptclauses
print ("Handling multiple exceptions")
try:
numerator=50
denom=int(input("Enter the denominator:"))
print (numerator/denom)
print ("Division performed successfully") except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
In the code, two types of exceptions (ZeroDivisionError and ValueError) are handled using two except blocks for a single try block.
Program: Use of except without specifying an exception
If the above code is executed, and the denominator entered is 0 (zero), the handler for ZeroDivisionError exception will be searched,
FINALLY CLAUSE
The try statement in python can also have an optional finally clause.
The finally block contains code that must execute, whether or not an exception was raised in the `try` block. If used, finally
should always be placed at the end of try clause, after all except blocks and the else block.
It ensures that certain actions are taken regardless of the outcome.
Program: Use of finally clause
print ("Handling exception using try...except...else...finally") try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)
finally:
print ("OVER AND OUT")
In the above program, the message “OVER AND OUT” will be displayed irrespective of whether an exception is raised or not.