0% found this document useful (0 votes)
30 views4 pages

Exception Handling

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)
30 views4 pages

Exception Handling

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
You are on page 1/ 4

Exception Handling - Errors are problems in a program due to which the program will stop the

execution. Error in Python can be of two types:

 Syntax Errors - errors that are detected when we have not followed the rules while writing a
program or skip some syntax. These errors are also known as ‘parsing errors’. When a syntax error
is encountered, Python displays the name of the error and a small description about the error.

Eg:

1. a=10 2. a=10
if(a/2) print ”a”
print(“a is even”)

output: output:
SyntaxError SyntaxError
(colon ‘:’ is missing in (Parenthesis is missing in print
if statement)

 Exceptions - is a Python object that represents an error. Exceptions are raised when the program
is syntactically correct, but the code results in an error. This error does not stop the execution of
the program, however, it changes the normal flow of the program.
Commonly occurring exceptions are usually defined in the compiler/interpreter. These are called
built-in exceptions.

Name of the Built-in Description


Exception
SyntaxError raised when there is an error in the syntax of the Python code.

ValueError raised when a built-in method or operation receives an argument that


has the right data type but mismatched or inappropriate values.
IOError raised when the file specified in a program statement cannot be
opened.
KeyboardInterrupt raised when the user accidentally hits the Delete or Esc key while
executing a program due to which the normal flow of the program is
interrupted.
ImportError raised when the requested module definition is not found.
EOFError raised when the end of file condition is reached without reading any
(End of file) data by input().
ZeroDivisionError raised when the denominator in a division operation is zero.
IndexError raised when the index or subscript in a sequence is out of range.
NameError raised when a local or global variable name is not defined.
IndentationError raised due to incorrect indentation in the program code.
TypeError raised when an operator is supplied with a value of incorrect data
type.
OverFlowError raised when the result of a calculation exceeds the maximum limit for
numeric data type.

Example:

ZeroDivisionError TypeError NameError


marks = 100 x=5 x=10
a = marks/0 y = "hello" Prnt(x)
print(a) z=x+y

raise Statement - Programmers can also forcefully raise exceptions in a program using the raise
statements. raising an exception involves interrupting the normal flow execution of program and
jumping to that part of the program (exception handler code) which is written to handle such
exceptional situations.
syntax:
raise exception-name[(optional argument)]

Eg: num = [10,20,30,40]


length=10
if length > len(num):
raise IndexError
print(“No execution”)
else:
print(“length”)

Handling Exceptions - technique that helps in capturing runtime errors and handling them to avoid
the program getting crashed. This is done by writing additional code in a program to give proper
messages or instructions to the user on encountering an exception. Exception Handling can be done
by try-except-else-finally method.

 try - except : try statements are used to catch exceptions and except statements are used to handle
exceptions. Statements that can raise exceptions are wrapped inside the try block and the
statements that handle the exception are written inside 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.

The syntax of try- except clause is as follows:

try:
[ program statements where exceptions might occur]
except [exception-name]:
[ code for exception handling if the exception-name error is encountered]

Eg: The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")

output: An exception occurred

Eg: Here we are trying to access the list element. The second print statement tries to access the
fourth element of the list which is not there and this throws an exception. This exception is then
caught by the except statement.
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")

output:
Second element = 2
An error occurred

Many Exceptions –

Eg: Print one message if the try block raises a NameError and another for other errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

Output: Variable x is not defined

Eg: def fun(a):


if a < 4:
b = a/(a-3)
print("Value of b = ", b)
try:
fun(3)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")

Output: ZeroDivisionError Occurred and Handled

 try-except-else - if there is no error in try block then none of the except blocks will be executed.
The statements inside the else clause will be executed.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception

Eg:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")

Output:
Hello #try executed
Nothing went wrong #else executed because no error in try

 try-except-finally - will be executed regardless if the try block raises an error or not.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
finally:
# Some code .....(always executed)

Eg:
try: # x is not defined
print(x)
except:
print("Something-went-wrong")
finally:
print("The 'try except' is finished")

output:
Something-went-wrong #except executed because x is not defined in try
The 'try except' is finished #finally executed

You might also like