[go: up one dir, main page]

0% found this document useful (0 votes)
17 views11 pages

Exception Handling

ex

Uploaded by

dhruvkuamr46
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)
17 views11 pages

Exception Handling

ex

Uploaded by

dhruvkuamr46
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/ 11

EXCEPTION HANDLING

Introduction
 In Python, exceptions are errors that get triggered automatically.
However, exceptions can be forcefully triggered and handled through program code.

 Syntax Errors
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.

 When a syntax error is encountered while working in shell mode, Python displays the name of the error and a small
description about the error
Similarly, when a syntax error is encountered while running a program in script mode a dialog box specifying the name of
the error and a small description about the error is displayed.
Exceptions

• An exception is a Python object that represents an error.


• When an error occurs during the execution of a program, an exception is said to have been raised.
• Such an exception needs to be handled by the programmer so that the program does not terminate
abnormally.

Built-in Exceptions
• Commonly occurring exceptions are usually defined in the compiler/interpreter. These are called built-in
exceptions.

• Python’s standard library is an extensive collection of built-in exceptions that deals with the commonly
occurring errors (exceptions) by providing the standardized solutions for such errors.

NOTE :
A programmer can also create custom exceptions to suit one’s requirements. These are called user-defined
exceptions.
Different types of exceptions in python:

• SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code, such as a
misspelled keyword, a missing colon, or an unbalanced parenthesis.
• TypeError: This exception is raised when an operation or function is applied to an object of the wrong
type, such as adding a string to an integer.
• NameError: This exception is raised when a variable or function name is not found in the current scope.
• IndexError: This exception is raised when an index is out of range for a list, tuple, or other sequence
types.
• KeyError: This exception is raised when a key is not found in a dictionary.
• ValueError: This exception is raised when a function or method is called with an invalid argument or
input, such as trying to convert a string to an integer when the string does not represent a valid integer.
• AttributeError: This exception is raised when an attribute or method is not found on an object, such as
trying to access a non-existent attribute of a class instance.
• IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails due to an
input/output error.
• ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.
• ImportError: This exception is raised when an import statement fails to find or load a module.
Raising Exceptions
• Each time an error is detected in a program, the Python interpreter raises (throws) an exception.
• 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 as shown in Figure, the message “OOPS : An Exception has occurred” is
displayed along with a brief description of the error.
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.

The important points regarding exceptions and their handling:


• Python categorises exceptions into distinct types so that specific exception handlers
(code to handle that particular exception) can be created for each type.

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

• The compiler or interpreter keeps track of the exact position where the error has occurred.

• Exception handling can be done for both user-defined and built-in exceptions.
Catching Exceptions
• An exception is said to be caught when a code that is designed to handle a particular exception is executed.
• Exceptions are caught in the try block and handled in the except block.
• Every try block is followed by an except block.
• 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 : Using try..except block
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”)
However, if an exception is raised for which no handler is created by the programmer, then such an exception can be
handled by adding an except clause without specifying any exception.
This except clause should be added as the last clause of the try...except 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 (without any specified exception) will be executed , so the message
“OOPS.....SOME EXCEPTION RAISED” will be displayed.
Finally Clause
The try statement in Python can also have an optional finally clause. The statements inside the finally block are always
executed regardless of whether an exception has occurred in the try block or not.
It is a common practice to use finally clause while working with files to ensure that the file object is closed. If used, finally
should always be placed at the end of try clause, after all except blocks and the else block.

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")
the message “OVER AND OUT” will be displayed irrespective of whether an exception is raised or not.

You might also like