Exception handling:
Python supports specific mechanism of catching and preventing errors that may occur.
This mechanism is called as exception handling.
Objectives:
1. Types of errors
2. How to avoid them
Exceptions and exception Handling:
Contradictory or unexpected situation during program execution, is Exception.
The way handle anomalous situations during run time called as exception handling
Two types of errors:
1. Compiler time errors:
Violation of programming language grammar rules i.e syntactically incorrect eg: print(“A” +2)
2. Runtime errors:
Error occurs during the runtime because of unexpected situations.
Such errors are handled through exception handling.
Advantages of exception handling:
1. Exception handling separated error handling code from normal code.
2. Remove error handling code from main program
3. It stimulates the error handling takes place at one place
4. It makes clear , fault – tolerant programs
Common examples of exceptions:
1. Divide by zero errors
2. Accessing elements beyond the range
3. Invalid input
4. Hard disk crash
5. Opening a non existing file
6. Heap memory exhausted.
Concept of exception handling:
Write code in such a way that it raises error flag every time when something goes wrong.
Raising of imaginary error flag is called throwing or raising an error.
When error is thrown exception handling is called trying to execute a block.
Terminology used in exception handling:
When to use Exception handling:
1. Processing exceptional situations
2. Processing exceptions for components that cannot handle them directly
3. Large projects that require uniform error processing.
Exception handling in python:
Exception handling in python involves try and except clauses in the format:
Syntax:
try:
write here code generate error
except:
code here what to do
eg:1
try:
print(“value of A is: “ , (10/0))
except :
print(“divide by zero error”)
General built in python exceptions:
Handling Multiple Errors:else part will gets executed if exception is raised:
try:
statement1
except 1:
statement2
except 2:
statement 3
else:
statement
Exception handling execution order:
1. Try suite is executed first
2. If try suite is not raised except suite will be executed, i.e ; named except suite
bounded will be execute, otherwise unnamed except suite is executed.
Finally Block: this block will always run.
Syntax:
try
st1……
except:
st2 …..
finally:
# always executes
Raising /Forcing an Exception: raise is keyword used to force for exception.