Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

Good Exceptions Notes

1. Errors can occur during compilation or runtime. Compile-time errors are called syntax errors and runtime errors are called exceptions. 2. Exceptions include errors like ZeroDivisionError, NameError, TypeError, and more. These represent problems like dividing by zero, undefined variables, incorrect data types, and other issues. 3. Exception handling uses try, except, else, and finally blocks to gracefully handle exceptions and allow programs to continue running despite errors.

Uploaded by

Prameela
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Good Exceptions Notes

1. Errors can occur during compilation or runtime. Compile-time errors are called syntax errors and runtime errors are called exceptions. 2. Exceptions include errors like ZeroDivisionError, NameError, TypeError, and more. These represent problems like dividing by zero, undefined variables, incorrect data types, and other issues. 3. Exception handling uses try, except, else, and finally blocks to gracefully handle exceptions and allow programs to continue running despite errors.

Uploaded by

Prameela
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Exceptions

Error:
An error is an action which is inaccurate or incorrect.
Error handling increases the robustness of the code
----- As it safe guards against potential failures that would
cause your program to exit in an uncontrolled fashion.
-------

Errors can be of various types : Broadly classified as

1. Errors identified during compilation or before execution-


Errors

2. Errors encountered during execution or run time by the


interpreter - Exceptions

 Errors which are identified during compilation can be -------


o Syntax Error

o Out of Memory Error

o Recursion Error etc…..

 Exceptions

Elaboration:

1.Error
 Syntax errors often called as parsing errors are predominantly
caused when the parser/interpreter detects a syntactic issue
in our code.
Let's take an example to understand it.
a=8
b = 10
c=ab
File "<ipython-input-8-3b3ffcedf995>", line 3
c=ab
^
SyntaxError: invalid syntax
 Memory errors are mostly dependent on your systems RAM and
are related to Heap. If you have objects larger than your memory
size, then you will see OutofMemoryError.

 Recursion Error It is related to stack and occurs when you call


functions. As the name suggests, recursion error transpires when
too many methods, one inside another is executed (one with an
infinite recursion), which is limited by the size of the stack.
2.Exceptions
Even if a statement or expression is syntactically correct, it
may cause an error when an attempt is made to execute it.
Such errors are called exceptions.

Example1:
x=int(input(“Enter the value of x”)
y= int(input(“Enter the value of y”)
Result=x/y
Print(“Result of Division is:”, Result)
X=2 y=1
Result=1

What if x=4 and y=0…..


We have a ZeroDivisionError exception raised to handle this
runtime error

Example2:
4+apple*3
Traceback(most recent call last):
NameError: name ‘apple’ is not defined
Example3:
>>> ‘4’+ 3
Traceback(most recent call last):
TypeError: Can’t convert ‘int’ object to str implicitly

Exceptions come in different types, and the type is printed as part


of the message:
the types in the example are  
ZeroDivisionError, NameError and TypeError

Exception Handling
The method/technique/piece of code adopted/written by
the programmer to handle the exceptions or run time errors
which are identified by the Interpreter is know as Exception
Handling
It is possible to write programs that handle exceptions by using the
Try, except,else,finally block.

Example:
def division(a , b):
c =(a / b)
return c
a=float(input("Enter the value of a= "))
b=float(input("Enter the value of b= "))
Result=division(a, b)
Print(“The result of Division is :”,Result)
No exception Handling

def division(a , b):


c =(a / b)
return c
a=float(input("Enter the value of a= "))
b=float(input("Enter the value of b= "))
try:
Result = division(a, b)
except ZeroDivisionError:
b=int(input(“Enter a new value of b”))
Result=division(a,b)
print(“Result of Division is :”,Result)
except NameError:
print(“ NameError Exception Caught”)
finally:
print(“Finally this module is successfully Executed”)
Exception Handling

This is just for knowledge… This is not there for exam


BuiltIn Exceptions
Arithmetic Error
 Zero Division Error
 OverFlow Error
 Floating Point Error

All of the above exceptions fall under the Arithmetic base class and


are raised for errors in arithmetic operations.
Zero Division Error
When the divisor (second argument of the division) or the
denominator is zero, then the resultant raises a zero division error.
c=50 c=50
b=10 b=0
try: try:
a=c/b a=c/b
print (a) print (a)
except ZeroDivisionError: except ZeroDivisionError:
print ("Zero Division Exception print ("Zero Division
Raised." ) Exception Raised." )
else: else:
print ("Success, no error!") print ("Success, no error!")
Finally: Finally:
Print(“These statements are Print(“These statements are
finally executed”) finally executed”)
After Execution: After Execution:
5 Zero Division Exception Raised
Success, no error !

OverFlow Error
The Overflow Error is raised when the result of an arithmetic
operation is out of range. OverflowError is raised for integers that
are outside a required range.

try: try:
import math import math
print(math.pi(10)) print(math.pi(10000000000))
except OverflowError: except OverflowError:
print ("OverFlow Exception print ("OverFlow Exception
Raised.") Raised.")
else: else:
print ("Success, no error!") print ("Success, no error!")
finally: finally:
print(“Program Executed”) print(“Program Executed”)
After Execution: After Execution:
Success, no error ! OverFlow Exception Raised.

Import Error
ImportError is raised when you try to import a module that does not
exist (unable to load) in its standard path or even when you make a
typo in the module's name.

Module1= “Math” Module1= “Stars”

try:
try:
import module1
import module1
except
except
ModuleNotFoundError:
ModuleNotFoundError:
print (" Module Not Found
print (" Module Not Found
Error Exception Raised.")
Error Exception Raised.")
else:
else:
print ("Module successfully
print ("Module successfully
Imported, no error!")
Imported, no error!")
finally:
finally:
print(“Program Executed”)
print(“Program Executed”)
After Execution:
After Execution:
Module Not Found
Module successfully Imported, no
Error Exception Raised.
error!

Lookup Error

Exceptions that occur when a key or index used on a mapping or


sequence of a list/dictionary is invalid or does not exists.
The two types of exceptions raised are:
1.IndexError
2.KeyError

Index Error

When you are trying to access an index (sequence) of a list that


does not exist in that list or is out of range of that list, an index
error is raised.

a = ['a', 'b', 'c'] a = ['a', 'b', 'c']


n=1 n=5
try: try:
print (a[n]) print (a[n])
except LookupError: except LookupError:
print ("Index Error Exception print ("Index Error Exception
Raised, list index out of range") Raised, list index out of range")
else: else:
print ("List value successfully print ("List value successfully
printed") printed")
Finally: Finally:
Print(“List is Evaluated”) Print(“List is Evaluated”)
After Execution: After Execution:
b Index Error Exception Raised, list
List value successfully printed index out of range
List is Evaluated

Key Error
If a key you are trying to access is not found in the dictionary,
a key error exception is raised.
a = {1:'a', 2:'b', 3:'c'} a = {1:'a', 2:'b', 3:'c'}
n= 1 n= 4

try: try:
print (a[n]) print (a[n])
except LookupError: except LookupError:
print ("Key Error Exception print ("Key Error Exception
Raised, Index out of range") Raised, Index out of range")
else: else:
print ("Success, no error!") print ("Success, no error!")
Finally: Finally:
Print(‘ Program successfully Print(‘ Program successfully
executed’) executed’)

After Execution: After Execution:


a Key Error Exception Raised,
Success, no error! Index out of range
Program successfully executed’ Program successfully executed’

Name Error
Name Error is raised when a local or global name is not found.
In the below example, Prime Minister variable is not defined. Hence,
you will get a name error.

Prime Minister= “Narendra (With Error)


Modi”

try: try:
print (Prime Minister) print (Prime Minister)
except NameError: except NameError:
print ("NameError: name print ("NameError: name
‘Prime Minister’ is not ‘Prime Minister’ is not
defined") defined")
else: else:
print (" Name of our Prime print (" Name of our Prime
Minister is successfully Minister is successfully
printed") printed")

After Execution: After Execution:


Narendra Modi NameError: name ‘Prime
Name of our Prime Minister Minister’ is not defined"
is successfully printed.

You might also like