0% found this document useful (0 votes)
2 views15 pages

Chapter 1 - Exception Handling in Python

Chapter 1 covers Exception Handling in Python, explaining its importance in managing errors that can cause program crashes. It details built-in exceptions, user-defined exceptions, and the syntax for handling exceptions using try, except, else, and finally clauses. The chapter also provides examples of common exceptions and how to implement exception handling effectively.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

Chapter 1 - Exception Handling in Python

Chapter 1 covers Exception Handling in Python, explaining its importance in managing errors that can cause program crashes. It details built-in exceptions, user-defined exceptions, and the syntax for handling exceptions using try, except, else, and finally clauses. The chapter also provides examples of common exceptions and how to implement exception handling effectively.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 1

Exception Handing in Python


CONCEPT
1. Introduction to Exception Handling
2. Built in Exceptions
3. User Defined Exceptions
4. Handling Exceptions
5. Python Exception Handling
6. Catching Exceptions
7. finally Clause
1. Introduction to Exception Handling
• Exception Handling is a feature in Python that allows us to handle errors and
prevent the program from crashing.
• Errors are problems due to which the program will stop the execution
• It may be due to syntax, runtime or logical errors.
Introduction to Exception
• Exception is an unexpected event that occurs during the execution of a
program. It is an error that occurs during runtime.
• Exception is a python object that represents an error. Even if the statement is
syntactically correct, there might be a situation in which an exception may
occur.
• Examples are dividing by O, accessing a variable without defining it, trying to
open a non-existing file.

Example:

Print (10/0)

Output: ZeroDivisionError: division by zero


2. Built-In Exceptions
Commonly occurring exceptions are usually defined in the interpreter. These are
called built-in exceptions
The programmer then has to take appropriate action to handle the exception.
Some of the built-in exceptions in Python are:
➢ Syntax Error: Syntax errors occur when we have not followed the rules/syntax of
a particular programming language while writing a program. These are
grammatical mistakes made.
Ex:
Print (“Hi)

Output:
SyntaxError: unterminated string literal (detected at line 1)

➢ ValueError: It is raised when an operation receives an argument that has the right
data type but mismatched or inappropriate values
Ex:
s1 = "Hello World"
print (float (s1))
Output:
ValueError: could not convert string to float: 'Hello World'
➢ IO Error: It is raised when the file specified in a program statement cannot be
opened.
Ex:
f= open("[Link]")
print([Link]())
Output:
f= open("[Link]")
FileNotFoundError: [Errno 2) No such file or directory:

➢ Import Error: It is raised when the requested module definition is not found.
OR When interpreter successfully located a module but fails to find a specific
function, class, or variable inside it.
Ex:
import xyz
Output:
import xyz
MOduleNotFoundError: No module named ‘xyz’

➢ ZeroDivisionError: It is raised when the denominator in a division operation


is zero
Ex:
100/0
Output:
100/0
ZeroDivisionError: division by zero

➢ Index Error: It is raised when the index or subscript in a sequence is out of


range.
Ex:
a = [10,20,5.6, "Hello all"]
print(a[5])
Output:
print(a[5])
IndexError: list index out of range

➢ Name Error: It is raised when a local or global variable name is not defined.
Ex:
➢ a= 10
➢ b=20
print (c)
Output:
NameError: name 'c' is not defined

➢ TypeError: Raised when an operation is applied to an object of inappropriate


type.
Ex:
1000+ "Hi"
Output
1000+ "Hi"
TypeError: unsupported operand type(s) for +: 'int' and 'str'

➢ IndentationError: Raised when there is incorrect indentation.


EX:
a=10
for i in range(4):
print(a+i)
Output:
expected an indented I

3. User Defined Exceptions


• A programmer can create exceptions to suit one's own requirements. These
are called as user-defined exceptions.
• It can be done using raise and assert statements.
• Once an exception is raised, no further statement in the current block of
code is executed.
• The control jumps to that part of program which is written to handle such
exceptions.

A. raise Statement: The raise statement can be used to throw an exception.


Syntax: raise Exception-name(argument)
The argument given is generally a string.
Ex:
a=-1
if (a<0):
raise Exception ("Give numbers greater than zero")
print ("No execution")
else:
print(“a”)
Output:
raise Exception ("Give numbers greater than zero")
Exception: Give numbers greater than zero
B. assert Statement: The assert statement is used to test an expression in the
program code.
• If the result is false, then exception is raised.
• It is used in the beginning of function or after a function call to
check for valid input.
• Syntax: 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
Ex:
a=1000
b=int(input("Enter value of b"))
assert (b>0), "Enter value greater than 0"
print (a*b)
Output:
Enter value of b5
5000
OR
Enter value of b-2
assert (b>0), "Enter value greater than 0"
AssertionError: Enter value greater than 0
4. Handling Exceptions
▪ Each and every exception has to be handled by the programmer to avoid the
program from crashing.
▪ This is done by writing additional code in the program to give proper
messages to the user on encountering exception known as exception handling.
▪ Need for Exception Handling:
o Python categorizes exceptions into different types so that specific
exception handlers be created for each type.
o The compiler or interpreter keeps track of the exact position where the
error has occurred.
o It can done for both user-defined and built-in exceptions
Steps / Process in Handling Exceptions

❑ When an error occurs, Python interpreter creates an object called the exception
object. This object contains information about the error like its type, and
position in the program where the error has occurred.
❑ The object is handed over to the runtime system so that it can find an
appropriate code to handle this particular exception. This process of creating
an exception object and handing it over to the runtime system is called
throwing an exception.
❑ The runtime system searches the entire program for a block of code, called the
exception handler that can handle the raised exception. It first searches the
current method in which the error has occurred. If not found, then it searches
the method from which this method was called.
❑ This search continues until exception handler is found. The entire list of
methods is called as call stack
❑ When a suitable handler is found in the call stack, it is executed by the
runtime process. This process of executing a suitable handler is known as
catching the exception.
❑ If the runtime system is not able to find an appropriate exception after
searching all the methods in the call stack, then the program execution stops.

5. Python Exception Handling


Syntax of Exception Handling:
try:
#Code that may cause Exception
except [Exception Name]: #Exception Name is optional
#Handling of Exception
else: (optional)
#Execute only if there is no Exception
finally: (optional)
#Code that always executes
• The try block allows you test the block of code for errors.
• The except block allows us to handle the exceptions.
• The else block allows us to execute the code when there is no error/exception.
• The finally block lets you execute the code regardless of the result of try and
except block.
• Statements that may cause exceptions are kept in try block and those that
handle them are kept in except block.

6. Catching Exceptions
• An exception is said to be caught when a code that is designed to handle a
particular exception is executed.
• Exceptions, if any, are caught in the try block and handled in the except
block.
• While executing the program, if an exception is encountered, further
execution of the code inside the try block is stopped and the control is
transferred to the except block.
Example of try-except clause.
print("Use of try-except clause")
try:
a=100b= int(input("Enter value of b"))
c=a/b
print("Result= ",c)
except ZeroDivisionError:
print("Value of b cannot be zero")
print("End")
Output:

Use of try-except clause Value of b cannot be


Enter value of b 5
Result= 20.0
End
OR
Use of try-except clause
Enter value of b 0
Value of b cannot be zero
End

Catching Multiple Exceptions:


• A try block can have more than one except clause to specify handlers for
different exception
• At most one handler is executed.
Syntax:
try:
#Code that may cause Exception
except specific-Exception: #Name
#statements
except specific-Exception2: #Name
#statements
except:(optional)
#statements

Ex:
print("Handling multiple exceptions")
try:
a=100
b= int(input("Enter value of b"))
c=a/bprint("Result= ",c)
except ZeroDivisionError:
print("Value of b cannot be zero")
except ValueError:
print("Enter only integers")
except:
print("Exception occurs")
print("End")
Output:
Handling multiple exceptions
Enter value of b 0
Value of b cannot be zero
End
OR
Handling multiple exceptions
Enter value of b abc
Enter only integers
End

Using Except without specifying an Exception:


print("Handling multiple exceptions")
try:
a=100
b= int(input("Enter the value of b"))
c=a/b
print (c)
except ValueError:
print("Enter only integers")
except:
print("Exception occurs")
print ("End")
Output:
Handling multiple exceptions
Enter value of b 0
Exception occurs
End

Using of try-except-else clause:


❑ In Python we can also use the else clause on the try-except clause which must
be present after all the except clauses.
❑ An except block will be executed only if some exception is raised in the try
block.
❑ The code enters the else clause only if the try-clause doesn't raise an exception
Ex:
print("Using else clause")
try:
a=100
b= int(input("Enter the value of b"))
c=a/b
except ValueError:
print("Enter only integers")
except Zero DivisionError:
print("Denominator cannot be 0")
else:
print("The result of division= ",c)
print("End")
Output:
Using else clause
Enter the value of b20
The result of division= 5.0
End
7. finally Clause:
• Finally block is always executed regardless of whether an exception has
occurred or not.
• Finally block should always be placed at the end of try clause, after all
except blocks and the else block
Ex:
print("Use of Finally block")
try:
a=100
b= int(input("Enter the value of b"))
c=a/b
print("Result = ",c)
except ZeroDivisionError:
print("Denominator cannot be 0")
finally:
print("This is finally block")
print("End")
Output:
Use of Finally block
Enter the value of b0
Denominator cannot be 0
This is finally block
End
OR
Use of Finally block
Enter the value of b 20
Result = 5.0
This is finally block End
QUESTION
1. Every syntax error is an exception but every exception cannot be a
syntax error." Justify the statement.
A syntax error is a specific type of exception that is detected when we have not
followed the rules of the particular programming language while writing a
program. On the other hand, an exception is a Python object that represents any
type of error or exceptional condition encountered during program execution.
This includes not only syntax errors but also runtime errors and logical errors.
2. What is the use of a raise statement? Write a code to accept two numbers
and display the quotient. Appropriate exception should be raised if the
user enters the second number (denominator) as zero
The raise statement is used to throw an exception during the execution of a
program.
a = float(input("Enter the numerator: "))
b = float(input("Enter the denominator: "))
if b == 0:
raise Zero DivisionError("Error: b cannot be zero.")
else:
c = a /b
print("Quotient:", c)

3. Consider the code given below and fill in the blanks.


print("Learning Exceptions....")
try:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
quotient = (num1/num2)
print("Both the numbers entered were correct")
except...... # to enter only integers
print("Please enter only numbers")
Except…… # Denominator should not be zero
print("Number 2 should not be zero")
else:
print("Great .. you are a good programmer")
………# to be executed at the end
print("JOB OVER... GO GET SOME REST")

You might also like