0% found this document useful (0 votes)
70 views45 pages

Exception Handling

Exception is an event that occurs during program execution that disrupts normal flow. Try and except blocks allow programs to handle exceptions gracefully. The try block contains code that may raise exceptions, and except blocks contain code that executes if an exception is raised. Finally blocks contain cleanup code that always executes regardless of exceptions. Multiple except blocks can handle different exception types.

Uploaded by

BJ Acharya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views45 pages

Exception Handling

Exception is an event that occurs during program execution that disrupts normal flow. Try and except blocks allow programs to handle exceptions gracefully. The try block contains code that may raise exceptions, and except blocks contain code that executes if an exception is raised. Finally blocks contain cleanup code that always executes regardless of exceptions. Multiple except blocks can handle different exception types.

Uploaded by

BJ Acharya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Exception Handling

What is Exception?
• An exception is an event, which occurs during the execution of a
program that disrupts the normal flow of the program’s instructions.
• In general, when a Python script encounters a situation that it cannot
cope with, it raises an exception.
• An exception is a Python object that represents an error.
• When a Python script (code) raises an exception, it must either handle
the exception immediately otherwise it terminates and quits.
Syntax Error vs Runtime Error
• Syntax Error are those error which is occurred due to the invalid syntax.
Code:
Runtime Errors:
• Runtime error are those error which is occurred at runtime(execution time).
• Code was syntactically correct, but the error occurs when the program is
executing.
• Runtime Error is also known as exception.
Code:

• If the value of b is 0.
• If the file ‘soft.txt’ is not
• If we input value ‘ten’ instead
available
of 10.
Runtime Error
?
?
What is
Exception?

=
Points to remember:

• Exception is the unwanted, unexpected event that occur during


execution of program that stops normal flow of your program.

• Exceptions are the Run-time Errors.

• As we know Exception terminate your program, it should be handled


by the programmer.
Exception-Handling?
• The process of handling the runtime errors (exception) occurred
during the execution of program is known as Exception-Handling.

• Defining alternative way to continue rest of the program normally.

• Objectives:
• In order to stop the abnormal flow of execution.
• Providing user-friendly message.
• Continuing rest of program.
Think:

• What are the errors that you get when an exception occur?
• From where they are coming?

• Python has many built-in exceptions which forces your program to output an
error when something in it goes wrong.
Exception Hierarchy in Python:

• These are the built-in exception in Python.


How Exception occur:
Throw object
at line 3.

PVM
Execute Match the
exception and
make the object of
Enter first num: 5 exception : throw
Enter the second num:0 that in your
program
Line 3 c = a/b
[Error occurred: cannot dived by 0]
How to handle this?: Exception Handling

• To handle exception
properly in Python, We
have four keywords: try,
except, else and finally.
Throw object
at line 3.

Execute PVM
Match the
exception and
Enter first num: 5 make the object of
Enter the second num:0 exception : throw
that in your
program
Line 3 c = a/b
[Error occurred: cannot dived by 0]
• try block :
• if the Python program contains suspicious code that may throw the exception,
we must place that code in the try block.

• The try block must be followed with the except block which contains a block
of code that will be executed if there is some exception in the try block.

Try block contains the


risky code
• except block –
• It contains the error handling code(alternative code).

• else block –
• It contains the code which should be executed if the exception do not
occur.

• finally block –
• it contains the code which should be executed whether exception
occur or not.
Code:

• If exception occur this will handle the code


and stops from abnormal termination and
executes rest of the code.
Control flow in try-except block
• Case-1: if exception do not occur ?

• Case-2: if exception occur at line3 ?


• Case-3: if exception occur at line 3 but ?
corresponding except block do not matched

• Case-4: if exception occur at line 6. ?


How to print except information:
Handling more than one exception:

Possible error:
ZeroDivisionError and ValueError

• Such method handling error is suitable if you want to print the type of error and
message.
• If you want to handle it by writing alternative code then it will have problem.
• Example – For every different questions in exam papers, we didn’t provide
same answer.
• If there is different question, we provide different answers.
Problems:

OR

• We can not write the above both different except block code in a single except block
because both exception do not occurred at same time.
• But point to remember is that both exception can occurred in same code at a single
time.
• So then what will be the solution?????  try block with multiple except blocks
try with multiple except blocks:

If exception occurred.
1
2

• The way of handling an exception is varied from exception to exception.


• Hence for every possible exception type, we have to take a separate except block. try with
multiple except block is possible and recommended to use.
• If try with multiple except blocks available then the order of these except blocks is important.
• Python virtual machine will always consider from top to bottom until matched except block
identified.
Maintain hierarchy:

?
?
Single except block that can handle multiple different exceptions:

• If handling code is same for multiple exceptions, then instead of


taking different except blocks, we can take single except block that
can handle all those exceptions.

• except(exception1,exception2, ….):
• except(exception1, exception2, …..) as msg:

• Parenthesis are mandatory and this group of exceptions internally


considered as tuple.
Example:
Default except Block:
• We can use default except block to handle
any type of exceptions.
• In default except block, generally we can
print exception information to console.
• Remember: Default except block always
should be last otherwise syntax error.
• Example:
Code Example:
Various possible combinations of except
block:
• except ZeroDivisionError:
• except (ZeroDivisionError):
• except ZeroDivsionError as msg:
• except(ZeroDivsionError) as msg:
• except(ZeroDivisonError, ValueError):
• except(ZeroDivisionError, ValueError) as msg:
• except
Questions:
• Except(ZeroDivisionError as msg): ?

• Except ZeroDivisonError, ValueError: ?

• Except (ZeroDivisionError, ValueError as msg): ?


finally block:
• It is not recommended to place clean-up code (resource deallocation
code like closing file connection, closing database connection etc)
inside try block, because there is no guarantee for execution of every
statement inside try block.
finally block:
• It is not recommended to place clean-up code inside except block,
because if there is no exception then except block won’t be executed.
finally block:
• Hence we required some place to maintain clean-up code which
should be executed always irrespective of whether exception raised or
not. Such type of best place is nothing but finally block.
• Hence main purpose of finally block is to maintain clean-up code.
Exercise:

Case1: if no exception occur. Case2: if exception raised Case3: if exception raised and
and handle not handle.

?
finally block:
• Finally block is always executed whether the exception occurred or
not.
• Is finally block is always executed?
• No, there is one situation, if the try block is executing and suddenly power is
off. In this situation the pvm get exit and the whole process will stop.
• os._exit(0)  0 means normal termination. non zero abnormal termination.
else block:
• Else block is executed if no exception occurred at try block.
else block:
• There is no chance of executing both except and else simultaneously.

• If we want to take else block, compulsory except block should be


there. i.e. else without except block is invalid.

• SyntaxError: invalid syntax


Code Example:
Types of Exceptions:
1. Predefined Exceptions:

2. User Define Exceptions


Predefined Exception:

• Also known as in-built exceptions or PVM exception.


• These will be raised automatically by Python Virtual Machine
whenever a particular event occurs.
• Print(5/0) # ZeroDivisionError
• X=int(‘five’) # ValueError
• F=open(‘abc.txt’) # if file is not there – FilenotFoundError
• L=[5,3] # print(l[5]) – IndexError
User Define Exception:
• Also known as customized Exception or Programmatic Exceptions.
• Sometimes we have to define and raise exceptions explicitly to
indicate that something goes wrong, such type of exceptions are
called user defined exceptions or customized exceptions or
programmatic exceptions.
• Programmer is responsible to define these exceptions and Python
Virtual Machine not having any idea about these. Hence we have to
raise explicitly based on our requirement by using ‘raise’ keyword.
How to define user defined exception:
• Every exception in Python is a class and it should be child class of
BaseException.
Code Example:
**The – End**

You might also like