0% found this document useful (0 votes)
13 views19 pages

Chapter 7

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 19

COMPUTER

PROGRAMMING USING
PYTHON
1

EXCEPTIONS

Dr Vipan Arora
Errors
2

Error in Python can be of two types


Syntax errors
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.

Dr Vipan Arora
Syntax Errors
3

 Syntax errors, also known as parsing errors, are perhaps


the most common kind of error you encounter while you
are still learning Python.

 The parser repeats the offending line and displays a little


‘arrow’ pointing at the earliest point in the line where the
error was detected. The error is detected at the token
preceding the arrow. File name and line number are
printed so you know where to look in case the input came
from a script.
Dr Vipan Arora
Exception
4

Exceptions are errors that raised during execution


time.
When that error occurs, Python generate an
exception that can be handled, which avoids your
program to crash.
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.

Dr Vipan Arora
5

Exceptions allow us to jump out of random, illogical


large chunks of codes in case of errors.
Exceptions allow programmers to jump an
exception handler in a single step, abandoning
all function calls. You can think exceptions to
an optimized quality go-to statement, in which the
program error that occurs at runtime gets easily
managed by the exception block.
When the interpreter encounters an error, it lets the
execution go to the exception part to solve and
continue the execution instead of stopping.
Dr Vipan Arora
Role of Exception Handler
6

 Error handling: The exceptions get raised whenever Python detects an


error in a program at runtime. As a programmer, if you don't want the
default behavior, then code a 'try' statement to catch and recover the
program from an exception. Python will jump to the 'try' handler when
the program detects an error; the execution will be resumed.
 Event Notification: Exceptions are also used to signal suitable
conditions & then passing result flags around a program and text them
explicitly.
 Terminate Execution: There may arise some problems or errors in
programs that it needs a termination. So try/finally is used that
guarantees that closing-time operation will be performed. The 'with'
statement offers an alternative for objects that support it.
 Exotic flow of Control: Programmers can also use exceptions as a
basis for implementing unusual control flow. Since there is no 'go to'
statement in Python so that exceptions can help in this respect.
Dr Vipan Arora
7

(a,b) = (6,0)
# simple use of try-except block for handling errors
try:
g = a/b
except ZeroDivisionError:
print ("This is a DIVIDED BY ZERO error")

Output
This is a DIVIDED BY ZERO error

Dr Vipan Arora
Processing of Exceptions
8

try/except: catch the error and recover from


exceptions hoist by programmers or Python itself.
try/finally: Whether exception occurs or not, it
automatically performs the clean-up action.
assert: triggers an exception conditionally in the
code.
raise: manually triggers an exception in the code.
with/as: implement context managers in older
versions of Python such as - Python 2.6 & Python
3.0.

Dr Vipan Arora
Try Expect
9

Try Except in Python: Try and Except statement is


used to handle these errors within our code in Python.
The try block is used to check some code for errors i.e.
the code inside the try block will execute when there
is no error in the program. Whereas the code inside
the except block will execute whenever the program
encounters some error in the preceding try block.
try:
# Some Code
except:
# Executed if error in the try block

Dr Vipan Arora
How try() works?
10

First, try clause is executed i.e. the code


between try and except clause.
If there is no exception, then only try clause will
run, except clause is finished.
If any exception occurred, try clause will be skipped
and except clause will run.
If any exception occurs, but the except clause within the
code doesn’t handle it, it is passed on to the
outer try statements. If the exception left unhandled,
then the execution stops.
A try statement can have more than one except clause

Dr Vipan Arora
Python code to illustrate working of try()
11

def divide(x, y):


try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
divide(3, 2)

Dr Vipan Arora
Else Clause
12

In python, you can also use the else clause on the try-except
block which must be present after all the except clauses. The
code enters the else block only if the try clause does not raise
an exception.

Try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
Dr Vipan Arora
Finally Keyword in Python
13

 Python provides a keyword finally, which is always executed after try


and except blocks. The final block always executes after normal
termination of try block or after try block terminates due to some
exceptions.
try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
finally:
# Some code .....(always executed)
Dr Vipan Arora
Assert statement
14

In Python, the assert statement is used to continue


the execute if the given condition evaluates to True.
If the assert condition evaluates to False, then it
raises the AssertionError exception with the
specified error message.
assert condition [, Error Message]
x = 10
assert x > 0
print('x is a positive number.')

Dr Vipan Arora
15

In the example, the assert condition, x > 0 evaluates


to be True, so it will continue to execute the next
statement without any error
The assert statement can optionally include an error
message string, which gets displayed along with
the AssertionError. Consider the following assert
statement with the error message
x=0
assert x > 0, 'Only positive numbers are
allowed' print('x is a positive number.')

Dr Vipan Arora
Raise statement
16

The raise keyword is used to raise an exception You


can define what kind of error to raise, and the text to
print to the user.Raise an error and stop the program
if x is lower than 0:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")

Dr Vipan Arora
Handling Multiple Exceptions
17

 Python has many built in exceptions that are raised when your
program encounters an error (something in the program goes
wrong).
 When these exceptions occur, the Python interpreter stops the
current process and passes it to the calling process until it is
handled. If not handled, the program will crash.
 For example, let us consider a program where we have
a function A that calls function B, which in turn calls function C.
If an exception occurs in function C but is not handled in C, the
exception passes to B and then to A.
 If never handled, an error message is displayed and our program
comes to a sudden unexpected halt.
 Python allows us to handle multiple exceptions in 2 ways:

Dr Vipan Arora
1. Using Multiple Except Blocks
18

We can catch multiple exceptions by sequentially


writing down except blocks for all those exceptions.
The pseudo-code looks like this:

try:
pass
except Exception1:
pass
except Exception2:
pass
Dr Vipan Arora
2. Using a Single Except Block
19

We can also catch multiple exceptions in a


single except block, if you want the same behavior for
all those exceptions.
This can avoid unnecessary duplication of code and can
save the programmer’s time if the output is the same
for multiple exceptions. Pseudo-code for the same:
try:
pass
except (Exception1, Exception2) as e:
pass

Dr Vipan Arora

You might also like