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

Exceptional Handling

Chapter 10 discusses exceptional handling in programming, detailing the types of errors such as syntax, semantic, run-time, and logical errors. It explains exceptions as errors detected during execution and introduces the try-except clause for handling these exceptions. Additionally, the chapter covers raising exceptions, defining custom exception classes, and provides examples of common built-in exceptions in Python.

Uploaded by

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

Exceptional Handling

Chapter 10 discusses exceptional handling in programming, detailing the types of errors such as syntax, semantic, run-time, and logical errors. It explains exceptions as errors detected during execution and introduces the try-except clause for handling these exceptions. Additionally, the chapter covers raising exceptions, defining custom exception classes, and provides examples of common built-in exceptions in Python.

Uploaded by

RANJIT Yadav
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

CHAPTER 10

EXCEPTIONAL HANDLING
EXCEPTIONAL HANDLING
ERRORS

Error is an abnormal condition


whenever it occurs execution of the
program is stopped.

An error is a term used to describe


any issue that arises unexpectedly that
cause a computer to not function properly.
Computers can encounter either
software errors or hardware errors.
ERRORS

Errors are mainly classified into following types.



1. Syntax Errors
2. Semantic Errors
3. Run Time Errors.
4. Logical Errors.
1. Syntax Errors

Syntax errors refer to formal


rules governing the construction of valid
statements in a language.

Syntax errors occur when rules


of a programming language are misused
i.e., when a grammatical rule of the
language is violated.
1. Syntax Errors

For instance in the following


program segment,
def main() : (Colon) Missing
a=10
b=3
print(“ Sum is “,a+b

) Missing
2. Semantic Errors

Semantics error occur when statements


are not meaningful
Semantics refers to the set of rules
which give the meaning of the
statement.
For example,
Rama plays Guitar
This statement is
syntactically and semantically correct
and it has some meaning.
2. Semantic Errors

See the following statement,


Guitar plays Rama
is syntactically correct (syntax is correct) but
semantically incorrect. Similarly, there are
semantics rules of programming language,
violation of which results in semantical
errors.
X*Y=Z
will result in semantical error as an
expression can not come on the left side of
an assignment statement.
3. Run Time Errors.

A Run time error is that occurs during


execution of the program. It is caused
because of some illegal operation taking
place.
For example
1. If a program is trying to open a file which
does not exists or it could not be
opened(meaning file is corrupted), results
into an execution error.
2. An expression is trying to divide a number
by zero are RUN TIME ERRORS.
4. Logical Errors.

• A Logical Error is that error which is


causes a program to produce incorrect
or undesired output.
for instance,
ctr=1;
while(ctr<10):
print(n *ctr)
Exceptions
Exceptions

What is an exception?

Even if a statement or expression is


syntactically correct, it may cause an error
when an attempt is made to execute it.
Errors detected during execution are
called exceptions
Exceptions

For Example
Exception Handling
When you run the program in Listing 11.3 or Listing 11.4, what
happens if the user enters a file or an URL that does not exist? The
program would be aborted and raises an error. For example, if you
run Listing 11.3 with an incorrect input, the program reports an IO
error as shown below:

c:\pybook\python CountEachLetter.py
Enter a filename: newinput.txt
Traceback (most recent call last):
File "CountEachLetter.py", line 23, in <module>
main()
File "CountEachLetter.py", line 4, in main
Infile = open(filename, "r"> # Open the file
IOError: [Errno 2] No such file or directory: 'newinput.txt'
14
The try ... except Clause

try:
<body>
except <ExceptionType>:
<handler>

15
The try ... except Clause
try:
<body>
except <ExceptionType1>:
<handler1>
...
except <ExceptionTypeN>:
<handlerN>
except:
<handlerExcept>
else:
<process_else>
finally:
<process_finally>
16
Raising Exceptions
You learned how to write the code to handle exceptions in the
preceding section. Where does an exception come from? How is
an exception created? Exceptions are objects and objects are
created from classes. An exception is raised from a function.
When a function detects an error, it can create an object of an
appropriate exception class and raise the object, using the
following syntax:

raise ExceptionClass("Something is wrong")

17
Processing Exceptions Using Exception Objects
You can access the exception object in the except
clause.
try
<body>
except ExceptionType as ex:
<handler>

18
Defining Custom Exception Classes
BaseException

Exception

StandardError

ArithmeticError EnvironmentError RuntimeError LookupError SyntaxError

ZeroDivionError IndentationError
IOError OSError IndexError KeyError
Handling Exceptions
Handling Exceptions

It is possible to write programs that


handle selected exceptions. Look at the
following example, which asks the user for
input until a valid integer has been
entered, but allows the user to interrupt
the program (using Control-C or whatever
the operating system supports); note that
a user-generated interruption is signalled
by raising the KeyboardInterrupt
exception.
Handling Exceptions

For Example
Handling Exceptions

The try statement works as follows.

First, the try clause (the statement(s)


between the try and except keywords) is
executed.

If no exception occurs, the except clause


is skipped and execution of the try
statement is finished.
Handling Exceptions

The try statement works as follows.

If an exception occurs during execution of


the try clause, the rest of the clause is
skipped. Then if its type matches the
exception named after the except keyword,
the except clause is executed, and then
execution continues after the try statement.
Handling Exceptions

The try statement works as follows.

If an exception occurs which does not


match the exception named in the except
clause, it is passed on to outer try
statements; if no handler is found, it is an
unhandled exception and execution stops
with a message as shown above.
The except Clause with No Exceptions
The except Clause with No Exceptions
You can also use the except
statement with no exceptions defined as
follows:
try:
You do your operations here;
except:
If there is any exception, then
execute this block…..
else:
If there is no exception then execute
this block. Contd..
The except Clause with No Exceptions

This kind of a try-except statement


catches all the exceptions that occur. Using
this kind of try-except statement is not
considered a good programming practice
though, because it catches all exceptions
but does not make the programmer
identify the root cause of the problem that
may occur.
Example
Example
raise statement
raise statement

You can raise an exception in your own


program by using the raise exception.

Raising an exception breaks current


code execution and returns the exception
back until it is handled.
Syntax:

raise [expression1[, expression2]]


raise Example
raise Example
Some common exceptions
Some common 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.
Some common exceptions

KeyboardInterrupt
Raised when the user hits the interrupt key
(normally Control-C or Delete).

EOFError
Raised when one of the built-in functions (input()
or raw_input()) hits an end-of-file condition (EOF)
without reading any data
CLASS TEST
CLASS TEST

Time: 40 Min Max Marks: 20

1. Explain the types of errors


05
2. What is an exception? Explain in detail 05

3. What is raise? explain in detail 05

4. Explain some of the common built in


exceptions provided in python 05

You might also like