0% found this document useful (0 votes)
18 views13 pages

Exception Handling

The document provides an overview of exception and file handling in Python, detailing various types of errors such as syntax, logical, and runtime errors. It explains how exceptions are raised and handled using try-except blocks, and discusses the use of built-in and user-defined exceptions, as well as the assert statement for error checking. Additionally, it covers the use of else and finally clauses in exception handling to ensure proper program execution and cleanup.

Uploaded by

hazel967377
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)
18 views13 pages

Exception Handling

The document provides an overview of exception and file handling in Python, detailing various types of errors such as syntax, logical, and runtime errors. It explains how exceptions are raised and handled using try-except blocks, and discusses the use of built-in and user-defined exceptions, as well as the assert statement for error checking. Additionally, it covers the use of else and finally clauses in exception handling to ensure proper program execution and cleanup.

Uploaded by

hazel967377
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/ 13

CHAPTER-1

EXCEPTION AND FILEHANDLINGIN PYTHON


INTRODUCTION
 While executing a Python program, the program does not execute at all or the program executes but generates unexpected
output or behaves abnormally .
 These occur when there are syntax errors, runtime errors or logical errors in the code.
 In Python, exceptions are errors that get triggered automatically.
 However, exceptions can be forcefully triggered and handled through program code.

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:

In script mode, Syntax error is encountered while running a program

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

The raise statement


 The raise statement can be used to throw an exception.
 The syntax of raise statement is:
raise exception-name[(optional argument)]
 The argument is generally a string that is displayed when the exception is raised.
 For example, when an exception is raised, the message “OOPS: An Exception has occurred” is displayed along with a
brief description of the error.

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

Use of assert statement:


print("use of assert statement") def negativecheck(number):
assert(number>=0), "OOPS... Negative Number“
print(number*number) print (negativecheck(100)) print
(negativecheck(-350))

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

Need for Exception Handling


 Exception handling is being used not only in Python programming
but in most programming languages like C++, Java, Ruby, etc.
 It is a useful technique that helps in capturing runtime errors and handling them so as to avoid the program getting crashed.
 Following are some of the important points regarding exceptions and their handling:
 a) Python categorizes exceptions into distinct types so that specific exception handlers (code to handle that
particular exception) can be created for each type.
 b) Exception handlers separate the main logic of the program from the error detection and correction code.
The segment of code where there is any possibility of error or exception, is placed inside one block. The code to be
executed in case the exception has occurred, is placed inside another block. These statements for detection and
reporting the exception do not affect the main logic of the program.
 c) The compiler or interpreter keeps track of the exact position where the error has occurred.
 d) Exception handling can be done for both user-defined and built-in exceptions.

Process of Handling Exception


 When an error occurs, Python interpreter creates an object called the exception object.
 This object contains information about the error like its type, file name and position in the program where the error has occurred.
 The object is handed over to the runtime system so that it can find an appropriate code to handle this particular exception. This process
of creating an exception object and handing it over to the runtime system is called throwing an exception.
 A runtime system refers to the execution of the statements given in the program.
Process of Handling Exception

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

print ("Handling exceptions without naming them")


try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print ("Division performed successfully")
except ValueError:
print ("Only INTEGERS should be entered")
except:
print(" OOPS.....SOME EXCEPTION RAISED")

 If the above code is executed, and the denominator entered is 0 (zero), the handler for ZeroDivisionError exception will be searched,

Since it is not present, the last except clause will be executed


try...except…else clause
 We can put an optional else clause along with the try...except clause.
 An except block will be executed only if some exception is raised in
the try block.
 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.
Program: Use of else clause
print ("Handling exception using try...except...else") 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 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.

Recovering and continuing with finally clause


 If an error has been detected in the try block and the exception has been thrown, the appropriate except block will be
executed to handle the error.
 But if the exception is not handled by any of the except clauses, then it is re-raised after the execution of the finally block.
 If any other type of error occurs for which there is no handler code (except clause) defined, then also the finally clause will
be executed first.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy