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

UNIT-V - Part-1 (Error and Exceptions)

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 19

Python Programming for Problem

Solving

Unit-5: Error & Exceptions

Mr. N. Bharath Kumar


Assistant Professor
Department of EEE

Department of Electrical and Electronics Engineering N. Bharath Kumar1


Error and Exceptions
• Errors are the problems in a program due to which the
program will stop the execution.
• Exceptions are raised when some internal events occur
which changes the normal flow of the program (Errors occur
at runtime are called exceptions).
• An exception is a Python object that represents an error.
• When a Python script raises an exception, it must either
handle the exception immediately otherwise it would
terminate and come out.
• Two types of Error occurs in python.
1. Syntax errors
2. Logical errors (Exceptions)
Department of Electrical and Electronics Engineering N. Bharath Kumar
Syntax Errors
• Error caused by not following the proper structure (syntax) of the
language is called syntax error or parsing error.

Ex:
amount = 10000
if(amount>2999)
print(“Hello”)
Output:
File "<ipython-input-2-a0933a876a76>", line 2
if(amount>2999)
^
SyntaxError: invalid syntax

• It returns a syntax error message because after if statement a colon : is


missing. We can fix this by writing the correct syntax.

Department of Electrical and Electronics Engineering N. Bharath Kumar


Logical Errors
• Errors that occur at runtime (after passing the syntax test) are called exceptions or
logical errors.
• For example, when we divide any number by zero
then ZeroDivisionError exception is raised, or when we import a module that does
not exist then ImportError is raised.
• Whenever these types of runtime errors occur, Python creates an exception
object. If not handled properly, it prints a traceback to that error along with some
details about why that error occurred.
Ex:
a = 100 / 0
print(a)
Output:
ZeroDivisionError Traceback (most recent call last)
<ipython-input-5-fab4c2b60b43> in <module>
----> 1 a = 100 / 0
2 print(a)

ZeroDivisionError: division by zero


Department of Electrical and Electronics Engineering N. Bharath Kumar
Logical Errors

• Illegal operations can raise exceptions.


• There are plenty of built-in exceptions in Python that are raised
when corresponding errors occur.
• We can view all the built-in exceptions using the built-in local()
function.

Ex:
print(dir(locals()['__builtins__']))

• locals()['__builtins__'] will return a module of built-in


exceptions, functions, and attributes.
• dir allows us to list these attributes as strings.

Department of Electrical and Electronics Engineering N. Bharath Kumar


Logical Errors
Example2:
while True:
x = int(input("Please enter a number: "))
print("example on exception")
print(x)
Output:
Please enter a number: 6
example on exception
6
Please enter a number: a
---------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-9-829122c8c327> in <module>
1 while True:
----> 2 x = int(input("Please enter a number: "))
3 print("example on exception")
4 print(x)
ValueError: invalid literal for int() with base 10: 'a'
Department of Electrical and Electronics Engineering N. Bharath Kumar
Python Built-in Exceptions or Standard Exceptions
Exception Cause of Error
BaseException This is the base class for all built-in exceptions
AttributeError An AttributeError is raised when an attribute reference or assignment fails such as when a non-
existent attribute is referenced.
EOFError Raised when the input() functions hits end-of-file condition with out reading the data.

FloatingPointError Raised when a floating point operation fails.


ImportError Raised when the imported module is not found.
IndexError Raised when index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
MemoryError Raised when an operation runs out of memory.
ZeroDivisionError Raised when second operand of division or modulo operation is zero.

Department of Electrical and Electronics Engineering N. Bharath Kumar


Python Built-in Exceptions or Standard Exceptions

Exception Cause of Error


NameError Raised when a variable is not found in local or global scope.
OverflowError Raised when result of an arithmetic operation is too large to be represented.

RuntimeError Raised when an error does not fall under any other category.
SyntaxError Raised by parser when syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tabs and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
TypeError Raised when a function or operation is applied to an object of incorrect type.

ValueError Raised when a function gets argument of correct type but improper value.

Department of Electrical and Electronics Engineering N. Bharath Kumar


Error/Exception Handling
• Python has many built-in exceptions that are raised when your program
encounters an error (something in the program goes wrong).
• When these exceptions occur, the Python interpreter stops the current
process and passes it to the calling process until it is handled. If not handled,
the program will crash.
• For example, let us consider a program where we have a function A that
calls function B, which in turn calls function C. If an exception occurs in
function C but is not handled in C, the exception passes to B and then to A.
• If never handled, an error message is displayed and our program comes to a
sudden unexpected halt.
• Exceptions can be generally handled using
1. try… except statement
2. try… except…else statement
3. try… except…finally statement

Department of Electrical and Electronics Engineering N. Bharath Kumar


Error/Exception Handling
1) try… except statement:
• Python uses try… except statement to handle exceptions.
• A code which can raise an exception is placed inside the try block and the
code that handles exception is written in except block.
• A try statement may have more than one except clause, to specify handlers
for different exceptions. At most one handler will be executed.
• The body of each except clause is known as an exception handler
• A single try statement can have multiple except statements. This is useful
when the try block contains statements that may throw different types of
exceptions.
Syntax:
try:
You do your operations here;
except Exception I:
If there is ExceptionI, then execute this block.
except Exception II:
If there is ExceptionII, then execute this block.
Department of Electrical and Electronics Engineering N. Bharath Kumar
Error/Exception Handling

• First, the try clause is executed.


• If an exception occurs during execution of the try clause, the rest
of the clause is skipped.
• Then if its type matches the exception named after
the except keyword, the except clause is executed, and then
execution continues.
• If an exception occurs which does not match the exception named
in the except clause, it is passed on to outer try statements; if no
handler is found, it is an unhandled exception and execution stops
with a message.

Department of Electrical and Electronics Engineering N. Bharath Kumar


Error/Exception Handling
Example: Output:
# import module sys to get the type of
exception The entry is a
Oops! <class 'ValueError'>
import sys occured.
randomList = ['a', 0, 2] Next entry.
for entry in randomList:
try: The entry is 0
print("The entry is", entry) Oops! <class
r = 1/int(entry) 'ZeroDivisionError'> occured.
break Next entry.
except:
print("Oops!",sys.exc_info()[0], The entry is 2
"occurred.") The reciprocal of 2 is 0.5
print("Next entry.")
print()
print("The reciprocal of", entry, "is",
r)
Department of Electrical and Electronics Engineering N. Bharath Kumar
Error/Exception Handling
2) try… except…else statement:
• If no exception occurs, then except clause is skipped and execution of
the else statement is finished.
• The code in the else-block executes if the code in the try: block does not raise an
exception.
Example:
while True:
try:
x = int(input("Please enter a number: "))
except ValueError:
print("Oops! That was no valid number. Try again...")
else:
print(x) Output:
break; Please enter a number: h
Oops! That was no valid number. Try again...
Please enter a number: 5
5
Department of Electrical and Electronics Engineering N. Bharath Kumar
Error/Exception Handling
3) try… except…finally statement:
• You can use a finally: block along with a try: block.
• A finally clause is executed before leaving the try statement, whether an
exception has occurred or not.
• The finally block is a place to put any code that must execute, whether the try-
block raised an exception or not.
Example: Output1:
a=int(input()) 5
b=int(input()) 6
try: 0.8333333333333334
c=a/b IT IS ALWAYS EXECUTED
print(c) Output2:
except ZeroDivisionError as e: 5
print(e) 0
finally: division by zero
print("IT IS ALWAYS EXECUTED") IT IS ALWAYS EXECUTED

Department of Electrical and Electronics Engineering N. Bharath Kumar


Raising Exceptions
• In Python programming, exceptions are raised when errors occur at runtime.
• We can also manually raise exceptions using the raise keyword.
• We can optionally pass values to the exception to clarify why that exception was
raised.
Example:
try:
amount = int(input())
if amount < 2999:
raise ValueError(“Please add money in your account")
else:
print("You are eligible to purchase")
except ValueError as e:
print(e)
Output1: Output3:
2000 dfj
Please add money in your account invalid literal for int() with base 10:
Output2: 'dfj'
3000
You are eligible to purchase
Department of Electrical and Electronics Engineering N. Bharath Kumar
User-Defined Exceptions

• Python also allows you to create your own exceptions by deriving classes
from the standard built-in exceptions.
• In Python, users can define such exceptions by creating a new class.
• This exception class has to be derived, either directly or indirectly,
from Exception class.
Syntax:
class user_defiend_exception_class_name(Exception):

Department of Electrical and Electronics Engineering N. Bharath Kumar


User-Defined Exceptions
Ex:

class Error(Exception):
"""Base class for other exceptions"""
pass

class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass

class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass

# you need to guess this number


number = 10

Department of Electrical and Electronics Engineering N. Bharath Kumar


User-Defined Exceptions
Ex:
# user guesses a number until he/she gets it right
while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()

print("Congratulations! You guessed it correctly.")


Department of Electrical and Electronics Engineering N. Bharath Kumar
User-Defined Exceptions
Output:

Enter a number: 12
This value is too large, try again!

Enter a number: 0
This value is too small, try again!

Enter a number: 8
This value is too small, try again!

Enter a number: 10
Congratulations! You guessed it correctly.

Department of Electrical and Electronics Engineering N. Bharath Kumar

You might also like