Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

Exception Handling

Presented By:
Dept. of Computer Science, KDARFS, Jamnagar
Syllabus (2023-24)

Exception Handling: Introduction, handling exceptions using try-except-finally blocks


Types of Errors
There are two types of errors :
(i) Compile-time errors. These are the errors resulting out of violation of
programming language’s grammar rules e.g., writing syntactically incorrect
statement like :
print ("A" + 2)
will result into compile-type error because of invalid syntax.
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.
Exception handling is a transparent and nice way to handle program errors.
Many reasons support the use of exception handling. In other words, advantages
of exception handling are :

(i) Exception handling separates error-handling code from normal code.

(ii) It clarifies the code (by removing error-handling code from main line of
program) and enhances readability.

(iii) It stimulates consequences as the error-handling takes place at one place and
in one manner.

(iv) It makes for clear, robust, fault-tolerant programs.

So we can summarize Exception as :


It is an exceptional event that occurs during runtime and causes normal program
flow to be disrupted.
Some common examples of Exceptions are :

 Divide by zero errors

 Accessing the elements of an array beyond its range

 Invalid input

 Hard disk crash

 Opening a non-existent file

 Heap memory exhausted


What is an Exception?
An exception in Python is an incident that happens while executing a
program that causes the regular course of the program's commands to be
disrupted.

When a Python code comes across a condition it can't handle, it raises an


exception.

An object in Python that describes an error is called an exception.

When a Python code throws an exception, it has two options: handle the
exception immediately or stop and quit.
Example (Syntax Error)
When the interpreter identifies a statement that has an error, syntax errors occur.
Consider the following scenario:

There was one unclosed bracket in this case. Close it and return the program:
Example (Run-time Error)

 We encountered an exception error after executing this code.


 When syntactically valid Python code produces an error, this is the kind of error that arises.
 The output's last line specified the name of the exception error code encountered.
 Instead of displaying just "exception error", Python displays information about the sort of exception
error that occurred.
 It was a NameError in this situation.
 Python includes several built-in exceptions. However, Python offers the facility to construct custom
exceptions.
General Built-in Exceptions
Commonly occurring exceptions are usually defined in the compiler/interpreter. These are called
built-in exceptions.
Built-in Exceptions …………
Let see some Exceptions
When to Use Exception Handling
The exception handling is ideal for :
• processing exceptional situations.
• processing exceptions for components that cannot handle
them directly.
• large projects that require uniform error-processing.
Process of Exception Handling in Python

Exception Handling in Python involves the use of try and except clauses in
the following format
See, now the output produced does not show the scary red-coloured standard error message ; it is now
showing what you defined under the exception block.
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’

ok = False
while not ok :
try :
numberString = input("Enter an integer:")
n = int(numberString)
ok = True
except :
print ("Error! Not a valid integer.")
Program to handle exception while opening a file.

try:
my_file = open("myfile.txt", "r")
print (my_file.read())
except:
print ("Error opening file")

The above program will open the file successfully if the file myfile.txt exists and contains some data
otherwise it shows an output as :

Now the above output may be of one of the two reasons :


(i) the file did not exist or
(ii) there was no data in the file.

But the above code did not tell which caused the error
You can also provide a second argument for the except block, which gives a reference to the
exception object. You can do it in following format :

try:
# code
except <ExceptionName> as <exArgument> :
# handle error here
Handling Multiple Errors
• Multiple types of errors may be captured and processed differently.
• It can be useful to provide a more exact error message to the user than a simple “an error has
occurred.”
• In order to capture and process different type of exceptions, there must be multiple exception blocks
– each one pertaining to different type of exception.

The last else : clause will execute if there is no exception raised, so you may put your code that
you want to execute when no exceptions get raised.
Exception Handling – 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.
The finally Block

You can also use a finally: block along with a try: block, just like you use except:
block, e.g., as :

The difference between an except: block and the finally: block is that the finally: block is a place
that contains any code that must execute, whether the try: block raised an exception or not.
Raising/Forcing an Exception(raise Statement)
You may use the raise keyword to raise/force an exception. That means, you as
programmer can force an exception to occur through raise keyword. It can also pass a
custom message to your exception handling module.

The exception raised in this way should be a pre-defined Built-in exception.


Consider following code snippet that forces a ZeroDivisionError exception to occur
without actually dividing a value by zero :

try :
a = int(input("Enter numerator :"))
b = int(input("Enter denominator :"))
if b == 0 :
raise ZeroDivisionError(str(a) + "/0 not possible")
print (a/b)
except ZeroDivisionError as e :
print ("Exception", str(e))
The assert Statement
An assert statement in Python is used to test an expression in the program code.

If the result after testing comes false, then the exception is raised.

This statement is generally used in the beginning of the function or after a function call to
check for valid input.

The syntax for assert statement is:


assert Expression[,arguments]
Example - assert Statement

print("Enter the Numerator: ")


n = int(input())
print("Enter the Denominator: ")
d = int(input())
assert d != 0, "Denominator must not be 0"
print("n/d =", int(n/d))

You might also like