Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
101 views

Exception Handling in Python

Uploaded by

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

Exception Handling in Python

Uploaded by

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

EXCEPTION HANDLING IN PYTHON

INTRODUCTION:
Error in Python can be of two types i.e. Syntax errors and Exceptions.
Errors are problems in a program due to which the program will stop the
execution. On the other hand, exceptions are raised when some internal
events occur which change the normal flow of the program.

TYPES OF ERRORS:
(i)Compile-time errors. These are the errors resulting out of violation of
programming language’s grammar rules. All syntax errors are reported during
compilation.
(ii) Run-time errors. The errors that occur during runtime because of unexpected
situations. Such errors are handled through exception handling routines of Python.

Syntax Error:
These are the errors resulting out of violation of programming language’s grammar
rules. All syntax errors are reported during compilation. Example:

Exception: Exceptions are unexpected events or errors that occur during the
execution of a program, such as a division by zero or accessing an invalid memory
location. These events can lead to program termination or incorrect results.
“It is an exceptional event that occurs during runtime and causes normal
program flow to be disrupted.”

Observe that there is nothing wrong with the program syntax, it is only when we try
to divide an integer with zero, an exception is generated.

Exception (Examples):
Example 1:

Only When we are trying to access a list


element with an non existing index an
exception is generated.

\
Example 2:

Only When we are trying to convert a


string to integer the Exception
generated.

What is Exception Handling?


 Exception handling in Python is a mechanism used to handle runtime errors that
occur during the execution of a Python program.
 Exception handling allows a program to gracefully handle such exceptions and
recover from errors by taking corrective actions instead of terminating abruptly.
 In Python, exception handling is implemented using a try-except block

Exception Handling using. try and except Block:


 The try and except block in Python is a way to handle exceptions or errors that
may occur during code
execution.
 This mechanism prevents
the program from crashing
by allowing it to continue
running even if an error is
encountered.
 In a try block, you write the code that might raise an exception.
 If an exception occurs, the code execution jumps to the corresponding except
block, where you can handle the error or take alternative actions
Exception (Example-1):

Exception (Example-1):
Write a program to ensure that an integer
is entered as input and in case any other
value is entered, it displays a message –
‘Not a valid integer’

DIFFERENT TYPES OF EXCEPTIONS IN PYTHON:


In Python, there are several built-in exceptions that can be raised when an error occurs during
the execution of a program. Here are some of the most common 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.
 KeyboardInterrupt: raised when the user inputs interrupt keys (Ctrl + C or Delete).
 MemoryError: raised when programs run out of memory.
 AssertionError: raised when the assert statement fails.
 IndentationError: occurs when there is a wrong indentation.

Second Argument of the Exception Block:


We can also provide a second argument (optional) for the except block, which
gives a reference to the exception object.
Handling Multiple Errors:
Handling multiple exceptions in Python allows a single try -except block to handle
different types of exceptions using multiple except blocks. This allows a program to
handle various types of errors that may occur during runtime and take corrective
measures accordingly.

In a try-except block, each except block is associated with a specific exception


type, and the block containing the code to handle that exception is executed if the
corresponding exception occurs in the try block. By handling multiple exceptions,
programmers can write more robust and less error -prone code.

Syntax:

Example: Program to handle multiple exceptions:

Execution Order:
The <try suite> is executed first ; if, during the course of executing the <try suite>,
an exception is raised that is not handled otherwise, and the <except suite> is
executed, with <name> bound to the exception, if found ; if no matching except
suite is found then unnamed except suite is executed.

finally Block:
The finally block is a part of the try-except block in Python that contains the code
that is executed regardless of whether an exception is raised or not. The syntax of
the try-except-finally block is as follows:

The try block contains the code that may raise an exception. If an exception occurs,
the control is transferred to the corresponding except block, which contains the
code to handle the exception. The finally block contains the code that is executed
after the try-except blocks, regardless of whether an exception occurred or not.

Example :Program using finally block

Example :Program using finally an else block together


In this example, if the user enters an invalid input or attempts to divide by zero, the
corresponding except block handles the exception and prints an error message to the
user. If no exception occurs, the else block is executed and prints the result.
Finally, the finally block is executed and prints a message to indicate the
completion of the program execution.

RAISE AN EXCEPTION:
 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.

Raise Statement:
The raise statement can be used to throw an exception.
Syntax:
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 below Figure, the message “OOPS : An Exception has
occurred” is displayed along with a brief description of the error.

The error detected may be a built-in exception or may be a user-defined one. Consider the
example given in below figure that uses the raise statement to raise a built-in exception called
IndexError.
Note: In this case, the user has only raised the exception but has not displayed any error message
explicitly.

In above 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

As we can see in above Figure, in addition to the error message displayed, Python also displays a
stack Traceback. This is a structured block of text that contains information about the sequence
of function calls that have been made in the branch of execution of code in which the exception
was raised. In the above figure, the error has been encountered in the most recently called
function that has been executed.

BENEFITS OF EXCEPTION HANDLING:


The advantages of exception handling are:
 Exception handling separates error – handling code from normal code.
 It clarifies the code and enhances readability.
 It stimulates consequences as the error- handling takes place at one place and in one manner.
 It makes for clear, robust, fault – tolerant programs.



You might also like