Introduction To Exception Handling in Python Class 12 Computer Science
Introduction To Exception Handling in Python Class 12 Computer Science
As a student of computer science, you know that many times while executing the
program we are getting some errors. These errors are categorized as follows:
As you have observed the above chart compile time errors are classified into two
categories:
1. Syntax Errors
2. Semantic Errors
Semantic Errors
Semantic Errors occur when the statement has no meaning in the program.
For example,
As the rule of RHS and LHS followed in Python, the left side statement cannot be
written in the right and vice versa.
For example
a=5 #Sattement 1
b=7 #Statement 2
a+b=res #Statement 3
In the above code, Statement 3 has a semantic error because an expression never
comes to the left side of the assignment operator. It should be always on the right
side.
Logical Errors
Quite often the programmer has written the code correctly without any syntax error
or semantic error. But didn’t get the exact result that is desired. This happens
because of the programmer’s mistake where the appropriate logic is not used.
Runtime errors
Sometimes the program is correct syntactically and semantically, but when the
programmer runs the program, errors occur. Such kinds of errors are called runtime
errors.
Runtime errors are very harder to detect in the programs. These errors may stop the
program execution abnormally or crash in between or runs infinite loops.
Basically, Python terminates the program when such errors occur. But it is not
advisable that the program crashes due to unwanted things.
Exceptions
An exception is a program event that occurs during program execution and disrupts
the flow of a program. When a Python program cannot cope with a situation, it raises
an exception. An exception is a Python object that represents an error.
Some syntax errors are also an exception. Whereas other exceptions can be generated
through code. Let us discuss some built-in exceptions in Python.
Built-in exceptions
The exceptions already defined by python are known as built-in exceptions. Python
standard library consists of large number of built-in exceptions. They are as follows:
Exception Explanation
1. raise statement
2. assert statement
raise statement
It is used to throw an exception. The syntax is as follows:
The optional argument is a string passed to the exception, that displays the
message. The exception may be user-defined or built-in.
Example:
d={'A':9,'B':10}
k=input("Enter key to search:")
if k in d.keys():
else:
Output:
assert statement
An assert statement in Python is used to check a condition in the program code. If
the result after evaluation is false, then the exception is raised.
This statement is generally used at the beginning of the function or after a function
call to check for valid input. The syntax for the assert statement is:
assert Expression[,arguments]
Example:
def odd_even(n):
print("Odd Number")
odd_even(6)
odd_even(5)
Step 2: The object is handed over to the runtime system to find an appropriate code
to handle exceptions. This process is called throwing an exception.
Step 3: The runtime system searches for a block of code known as an exception
handler that handles the raised error. First, it searches for the method by which the
error has occurred. If not found then it search method from which this method is
called. This process continues till the exception handler is found. When it found a
handler it will be executed. This process is known as catching.
Catching Exceptions
Catching exceptions refers to the execution of code that handles particular
exceptions. Any exception caught through try block and handled through except
block.
try and except block
The try block contains the actual codes that need to be executed. Every try block is
followed by except block. The exception handling code is written inside the except
block.
In the execution of the program, if an exception is raised the try block execution is
stopped and the control is shifted to except block. The syntax of try and except is as
follows:
try:
except [exception_name]:
try:
print(x)
except NameError:
Output:
try:
Output:
Example 3: ImportError
try:
import Datetime
print("Module")
except ImportError:
Example 4: ZeroDivisionError
try:
c=5/0
except ZeroDivisionError:
Example 5: IndexError
l=[11,45,67,89]
try:
print(l[5])
except IndexError:
print("Index not found")
Example 6: TypeError
try:
a=5
print(a+'b')
except TypeError:
print("Invalid Datatypes")
You can also raise exceptions without exception names in except block. Observe
this code:
try:
a=10 / 0
except:
print("Exception Raised...")
Example:
try:
result = 10 / 0
result = 10 +'d'
except ZeroDivisionError, TypeError as e:
print("Error occurred:", e)
In the above code, the ZeroDivisionError exception is raised in the first line, and the
relevant message is generated. If the first exception is not raised then it will jump to
another exception i.e. TypeError.
try:
result = 10 / 0
result = 10 + 'd'
except ZeroDivisionError as e:
print("Error occurred:", e)
print("Error occurred:",e1)
Use of else clause in exception handling
in Python
Now you are familiar with the process of exception handling, where except block will
be executed if any exception is raised in the try block. But when no error is reported,
then no except block will be executed. In this scenario else block comes into play a
role.
The else block in exception handling in Python will be executed in a similar manner
as it is executed in if…else, while..else etc. Observe this code:
try:
n1=int(input("Enter number1:"))
n2=int(input("Enter number2:"))
res=n1+n2
except ValueError:
else:
Finally Clause
The finally clause ends the exception-handling process. It bottom last clause after
handling all except clauses including else block. The finally clause always executes
at the end. Just have a look at the following:
The finally clause ends the exception-handling process. It bottom last clause after
handling all except clauses including else block. The finally clause always executes
at the end. Just have a look at the following:
print ("Handling multiple exceptions")
try:
n1=int(input("Enter number1:"))
n2=int(input("Enter number2:"))
res=n1+n2
except ValueError:
else:
finally:
try:
n1=int(input("Enter number1:"))
n2=int(input("Enter number2:"))
res=n1/n2
except ZeroDivisionError:
else:
finally:
Output:
After execution of finally block, Python transfers the control to a previously entered
try or to the next
higher level default exception handler. In such a case, the statements following the
finally block is executed. That is, unlike except, execution of the finally clause does
not terminate the exception. Rather, the exception continues to be raised after
execution of finally.
3. The statements inside the finally block are always executed regardless
of whether an exception occurred in the try block or not.
1. True
2. False
3. Depend on code
4. None of the above