0% found this document useful (0 votes)
40 views

Unit-II Exception Handling

Uploaded by

Dhruti Patel
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)
40 views

Unit-II Exception Handling

Uploaded by

Dhruti Patel
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/ 36

Unit-II – Exception

Handling &
Multithreading
Contents
• Exception Handling: Handling an exception, Exception
Hierarchy, The Exception Model, Run Time Errors,
try…….except…….else, try-finally-clause, Argument of an
exception, Python standard exceptions and user defined
exceptions, Handling IO Exceptions.
• Multithreading: Starting a new thread, the threading module,
synchronizing threads, race condition, multithreaded priority
queue.
Errors in Python
• Error in Python can be of two types i.e. Syntax errors and
Exceptions. Errors are the 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
changes the normal flow of the program.
• The difference between Syntax Error and Exceptions
• Syntax Error: As the name suggest this error is caused by
wrong syntax in the code. It leads to the termination of the
program.
Exceptions
• Exceptions: Exceptions are raised when the program is
syntactically correct but the code resulted in an error. This
error changes the normal flow of the program.
Introduction
• An exception is an error that happens during execution of a
program. When that error occurs, Python generate an
exception that can be handled, which avoids your program to
crash.
• When these exceptions occur, it causes the current process to
stop and passes it to the calling process until it is handled. If
not handled, our program will crash.
• For example, if function A calls function B which in turn calls
function C and an exception occurs in function C. If it is not
handled in C, the exception passes to B and then to A.
• If never handled, an error message is spit out and our program
come to a sudden, unexpected halt.
Python Exception Handling
◉ We can make certain mistakes while writing a program that lead to errors
when we try to run it. A python program terminates as soon as it encounters
an unhandled error. These errors can be broadly classified into two classes:
1. Syntax errors
2. Logical errors (Exceptions)
◉ Python Syntax Errors
◉ Error caused by not following the proper structure (syntax) of the language is
called syntax error or parsing error.
◉ Let's look at one example:
◉ As shown in the example, an arrow indicates where the parser ran into the
syntax error.
◉ We can notice here that a colon : is missing in the if statement.
Why Exception Handling
• Exceptions are convenient in many ways for handling errors
and special conditions in a program. When you think that you
have a code which can produce an error then you can use
exception handling.
Types of Exceptions
• IOError
• If the file cannot be opened.
• ImportError
• If python cannot find the module
• ValueError
• Raised when a built-in operation or function receives an
argument that has the right type but an inappropriate value
• EOFError
• Raised when one of the built-in functions (input() or raw_input())
hits an end-of-file condition (EOF) without reading any data
Syntax to Handle
• except IOError:
• print('An error occurred trying to read the file.')
• except ValueError:
• print('Non-numeric data found in the file.')
• except ImportError:
• print "NO module found"
• except EOFError:
• print('Why did you do an EOF on me?')
• except KeyboardInterrupt:
• print('You cancelled the operation.') except: print('An error
occurred.')
Keyword for Exception Handling

• Try
• Except
• Raise
• Else
• Finally
Handling an Exception (try)
• In Python, exceptions can be handled using a try statement.
• A critical operation which can raise exception is placed inside
the try clause and the code that handles exception is written
in except clause.
• It is up to us, what operations we perform once we have
caught the exception.
Catching Specific Exception (except)
• The code that follows the except statement is the program’s
response to any exceptions in the preceding try clause.
• A try clause can have any number of except clause to handle
them differently but only one will be executed in case an
exception occurs.
Raising an Exception (Raise)
• In Python programming, exceptions are raised when
corresponding errors occur at run time, but we can forcefully
raise it using the keyword raise.
• We can also optionally pass in value to the exception to clarify
why that exception was raised.
Finally Clause
• The try statement in Python can have an
optional finally clause. This clause is executed no matter what,
and is generally used to release external resources.
• For example, we may be connected to a remote data center
through the network or working with a file or working with a
Graphical User Interface (GUI).
• In all these circumstances, we must clean up the resource
once used, whether it was successful or not. These actions
(closing a file, GUI or disconnecting from network) are
performed in the finally clause to guarantee execution.
• Here is an example of file operations to illustrate this.
Example
Else
• A single try statement can have multiple except statements.
This is useful when the try block contains statements that may
throw different types of exceptions.
• You can also provide a generic except clause, which handles
any exception.
• After the except clause(s), you can include an else-clause. The
code in the else-block executes if the code in the try: block
does not raise an exception.
• The else-block is a good place for code that does not need the
try: block's protection.
Syntax
Demonstration-I
Output
Demonstration-II
Output
Demonstration-III
Output
Demonstration-IV
Output
Demonstration-V
Output
Customized Exception
• Python has numerous built-in exceptions that force your
program to output an error when something in the program
goes wrong.
• However, sometimes you may need to create your own
custom exceptions that serve your purpose.
• In Python, users can define custom exceptions by creating a
new class. This exception class has to be derived, either
directly or indirectly, from the built-in Exception class. Most of
the built-in exceptions are also derived from this class.

You might also like