Comprehensive notes Exception Handling in Python Class 12 Computer Science

In this article, we are going to discuss the newly added topic of Exception Handling in Python Class 12 Computer Science. CBSE released the syllabus on 31.03.2023 and now you all are aware that exception handling is added to this year’s syllabus of computer science. So let us begin!

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:

Errors in Python - Exception handling python

Compile Time Errors

Compile time errors occur when the programmer is compiling a program. The Python source code is checked for any violation of Python rules in the programming at compile time and if anything is not as per rule, it reports an error.

As you have observed the above chart compile time errors are classified into two categories:

  1. Syntax Errors
  2. Semantic Errors

Syntax Errors

A syntax error occurs when any of the Python programming rules are violated or the program is not written correctly as per the format required.

For Example,

x =+3 #statement 1

if a = (a+b) #Statement 2

In statement 1, =+ is used which is not the correct operator, the correct operator is +=. Hence the correct statement is x += 3.

In statement 2, = is used with it, which is incorrect. The correct statement is: a== (a+b)

So while writing a program, a programmer should ensure that the right code is written.

Syntax errors are reported by python interpreter with a full decription of error along with suggestions to rectify them.

Semantic Errors

Semantic Errors occur when the statement has no meaning in the program.

For example,

“Ayush is playing cricket.”

This is syntactically and semantically correct. But

“Cricket is playing Ayush.”

This is syntactically correct but semantically not.

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.

For example in place of addition, subtraction is done.

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 common Python exceptions are as follows:

Exceptionopening a file that is not present
Array out of rangeuser tries to access an element that is beyond the range from list
divide by zeroany number which is divided by zero – 5/0
invalid inputopening a file that is not present
opening a file that does not existsThe user has given incorrect input

Now let us start exception handling in Python class 12 computer science with the meaning of exception handling.

What is Exception Handling in Python Class 12 Computer Science?

The process of catching and preventing errors when they occurred is called exception handling. It is a mechanism to overrule the exceptions using some blocks.

In other words, way of handling unexpected error during runtime is called exception.

It is the concept of error handling when something goes wrong, tracking the error, and calling the handling code. The following terms are used for exception handling:

python exception handling terms

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:

ExceptionExplanation
ValueErrorIt is raised when a built-in method or operation mismatched or inappropriate values are provided as input.
IOErrorIt is raised when the file specified in a program statement cannot be opened.
KeyboardInterruptIt is raised when the user accidentally presses delete or esc key or cancels the execution.
ImportError It is raised when the specified module is not installed or not working.
EOFErrorIt is raised when the end of file condition is reached without reading any data by input().
ZeroDivisionErrorIt is raised when any number is having denominator zero.
IndexErrorIt is raised when the index or subscript in a sequence is out of range.
NameErrorIt is raised when a variable is accessed before declaration.
IndentationErrorIt is raised due to incorrect indentation in the program code.
TypeErrorIt is raised when an operator is supplied with a value of incorrect data type.
OverFlowErrorIt is raised when the result of a calculation exceeds the maximum limit for numeric data type.

Examples:

Python built-in exceptions - exception handling in python

Watch this video for an understanding:

User-defined exceptions

The exception created by the programmer according to the requirement of the program is called user-defined exceptions.

The user defined-exception can be created using two methods:

  1. raise statement
  2. assert statement

raise statement

It is used to throw an exception. The syntax is as follows:

raise exception-name[(optional argument)]

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():
  print("Key found in dict...")
else:
  raise KeyError("Key not present in dict...")

Output:

Comprehensive notes Exception Handling in Python Class 12 Computer Science

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]

On encountering an assert statement, Python evaluates the expression given immediately after the assert keyword. If this expression is false, an AssertionError exception is raised which can be handled like any other exception.

Example:

def odd_even(n):
  assert (n%2==0),"Even Number..."
  print("Odd Number")
odd_even(6)
odd_even(5)

Comprehensive notes Exception Handling in Python Class 12 Computer Science

Process of exception handling

The process of exception handling in python

Step 1: The exception object is created by a Python interpreter that contains information related to the error such as type, file name, and position where an error has occurred.

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.

Step 4: Finally the program gets terminated

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:
 program statement in which exception may occur
except [exception_name]:
 exception handler code

Example 1 : NameError Exception

try:
 print(x)
except NameError:
 print("Varibale is not defined...")

Output:

NameError - Exception

Example 2: ValueError Exception

try:
    a = int(input("Enter your age: "))
except ValueError:
    #Print message for ValueError
    print("Invalid input:Enter numbers only")

Output:

Comprehensive notes Exception Handling in Python Class 12 Computer Science

Example 3: ImportError

try:
    import Datetime
    print("Module")
except ImportError:

    print("Invalid module Can't import")

Example 4: ZeroDivisionError

try:
    c=5/0
except ZeroDivisionError:
    print("You cannot divide")

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:

print ("Handling multiple exceptions")
try:
    a=10 / 0
except:
    print("Exception Raised...")

Handling multiple exceptions

Multiple exceptions can be handled together using multiple exceptions with multiple exception handlers. There are two ways to handle multiple exceptions.

  1. Writing multiple exception handlers together
  2. Writing multiple exception handlers with separate except blocks

writing multiple exception handlers together

The multiple exception handlers can be written within one except block. When the first exception is raised it will stop execution and evaluate the first except block.

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.

Writing multiple exception handlers with separate except blocks

Multiple except blocks are required for this method. Observe the example:

try:
    result = 10 / 0
    result = 10 + 'd'
except ZeroDivisionError as e:
    print("Error occurred:", e)
except TypeError as e1:
    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:

print ("Handling multiple exceptions")
try:
    n1=int(input("Enter number1:"))
    n2=int(input("Enter number2:"))
    res=n1+n2
except ValueError:
    print("Enter integers only...")
else:
    print("The result is:",res)

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:

print ("Handling multiple exceptions")
try:
    n1=int(input("Enter number1:"))
    n2=int(input("Enter number2:"))
    res=n1+n2
except ValueError:
    print("Enter integers only...")
else:
    print("No exception raised...")
    print("The result is:",res)
finally:
    print("You have done it!!! Bye Bye")
Comprehensive notes Exception Handling in Python Class 12 Computer Science

If sometimes any exception which is not caught in exception handler, in this scenario too the finally clause will execute first and the exception is re-raised. Just observe this code:

print ("Handling multiple exceptions")
try:
    n1=int(input("Enter number1:"))
    n2=int(input("Enter number2:"))
    res=n1/n2
except ZeroDivisionError:
    print("Enter integers only...")
else:
    print("No exception raised...")
    print("The result is:",res)
finally:
    print("You have done it!!! Bye Bye")

Output:

exception handlng in python clas 12

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.

Leave a Reply