SlideShare a Scribd company logo
2
Most read
3
Most read
15
Most read
UNIT-5
Python Programming
Errors and Exceptions
N.JUNNUBABU. ASST PROF.
5.Errors and Exceptions
 There are two distinguishable kinds of errors:
1. syntax errors.
2. exceptions.
 5.1.Syntax Errors:
 Syntax errors, also known as parsing errors, are the most common kind of
errors.
Example:-
while True print(‘python programming')
SyntaxError: invalid syntax
 The parser repeats the offending line and displays a little ‘arrow’ pointing
at the earliest point in the line where the error was detected. in the
example, the error is detected at the function print(), since a colon (':') is
missing before it.
5.2.Exceptions
 Even if a statement or expression is syntactically correct, it may cause an
error when an attempt is made to execute it. Errors detected during
execution are called exceptions.
Example:-
>>> 10 * (1/0)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
10 * (1/0)
ZeroDivisionError: division by zero
 The string printed as the exception type is the name of the built-in
exception that occurred. This is true for all built-in exceptions, but need
not be true for user-defined exceptions.
5.3.Handling an Exceptions
 If you have some suspicious code that may raise an exception, you
can defend your program by placing the suspicious code in a try:
block. After the try: block, include an except: statement, followed by a
block of code which handles the problem as elegantly as possible.
Syntax:-syntax of try....except...else blocks
try:
You do your operations here
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Imp.. points above-mention syntax
Note:-
 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.
 You can also provide a generic except clause, which handles any exception.
 After the except clause(s), you can include an else-clause. The code in the
else block executes if the code in the try: block does not raise an
exception.
 The else-block is a good place for code that does not need the try:
block's protection.
Try…except…example:
 The try-except block is used to handle exceptions in python.
 When an exception occurs, it is caught by the except block. The catch
block cannot be used without the try block.
def divide(num1, num2):
try:
result = num1 // num2
remainder = num1 % num2
except ZeroDivisionError:
print("...You are dividing(divisor) by zero...")
else:
print("Your answer is(Gives only quotient):", result)
print("Your answer is(Gives only remainder) :", remainder)
num1=int(input("enter the num1(dividend) value:"))
num2=int(input("enter the num2(divisor) value:"))
divide(num1, num2)
Continue..
Finally block:-
You can use a finally: block along with a try: block. The finally: block is a place
to put any code that must execute, whether the try: block raised an exception
or not.
Output:-
enter the num1(dividend) value:128
enter the num2(divisor) value:14
Your answer is(Gives only quotient): 9
Your answer is(Gives only remainder) : 2
........................................................................
enter the num1(dividend) value:120
enter the num2(divisor) value:0
...You are dividing(divisor) by zero...
Try-finally example.
try:
a=int(input("entere a value:"))
b=int(input("entere b value:"))
c=a//b
except ZeroDivisionError:
print("division can't possible:(b=0)")
else:
print("a//b value:",c)
finally:
print(".....enter of program.....")
Output:-
entere a value:10
entere b value:0
division can't possible:(b=0)
.....enter of program.....
entere a value:10
entere b value:2
a//b value: 5
.....enter of program.....
5.4.Raising an Exceptions
 You can raise exceptions in several ways by using the raise statement. The
general syntax for the raise statement is as follows
Syntax:-raise [Exception [, args [, traceback]]]
Example:-
The sole argument to raise indicates the exception to be raised. If an
exception class is passed, it will be implicitly instantiated by calling its
constructor with no arguments:
raise ValueError # shorthand for 'raise ValueError()'
raise NameError('HiThere')
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
raise NameError('HiThere')
NameError: HiThere
Example.
The following example illustrates the use of raising an exception-
#!/usr/bin/python3
def functionName( level ):
if level <1:
raise Exception(level)
# The code below to this would not be executed
# if we raise the exception
return level
try:
l=functionName(-10)
print ("level=",l)
except Exception as e:
print ("error in level argument",e.args[0])
Output:-
error in level argument -10
5.5.Exception chaining
 Exception chaining happens automatically when an exception is
raised inside an except or finally section. Exception chaining can be
disabled by using from None idiom:
try:
open('database.sqlite')
except IOError:
raise RuntimeError from None
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError
5.6.User - Defined Exceptions
 Python also allows you to create your own exceptions by deriving classes
from the standard built-in exceptions. Example:-
class Error(Exception): """Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes: expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
 Most exceptions are defined with names that end in “Error”, similar to the
naming of the standard exceptions.
 Many standard modules define their own exceptions to report errors that
may occur in functions they define. More information on classes is
presented in chapter Classes.
5.7.Defining Clean-up Actions:-
 The try statement has another optional clause which is intended to define
clean-up actions that must be executed under all circumstances. For
example:
try:
raise KeyboardInterrupt
finally:
print('Goodbye, world!')
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
 If a finallyclause is present, the finally clause will execute as the last task
before the try statement completes. The finally clause runs whether or not the
try statement produces an exception.
 For example:
 the finally clause is executed in any event. In real world applications, the
finally clause is useful for releasing external resources (such as files or network
connections), regardless of whether the use of the resource was successful.
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
5.8.Predefined Clean-up Actions
 Some objects define standard clean-up actions to be undertaken when the
object is no longer needed, regardless of whether or not the operation using
the object succeeded or failed.
 The problem with this code is that it leaves the file open for an indeterminate
amount of time after this part of the code has finished executing. This is not an
issue in simple scripts, but can be a problem for larger applications.
The with statement allows objects like files to be used in a way that ensures they
are always cleaned up promptly and correctly.
 After the statement is executed, the file f is always closed, even if a problem was
encountered while processing the lines. Objects which, like files, provide
predefined clean-up actions will indicate this in their documentation.
for line in open("myfile.txt"):
print(line, end="")
with open("myfile.txt") as f:
for line in f:
print(line, end="")

More Related Content

PPTX
Python Flow Control
PPTX
Chapter 13 exceptional handling
PPTX
Data file handling in python introduction,opening & closing files
PDF
Python programming : Standard Input and Output
PPTX
Chapter 06 constructors and destructors
PDF
Python programming : Control statements
PPTX
String Manipulation in Python
PDF
Python recursion
Python Flow Control
Chapter 13 exceptional handling
Data file handling in python introduction,opening & closing files
Python programming : Standard Input and Output
Chapter 06 constructors and destructors
Python programming : Control statements
String Manipulation in Python
Python recursion

What's hot (20)

PPTX
List in Python
PDF
Python exception handling
PPTX
Print input-presentation
PDF
Python programming : Classes objects
PPTX
Stack and Queue
PPTX
Basics of Object Oriented Programming in Python
PPT
structure and union
PPTX
Conditional and control statement
PPT
Python Control structures
PDF
Python tuple
PDF
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
PDF
PPTX
Stacks in c++
PPTX
Preprocessor directives in c language
PPTX
Chapter 05 classes and objects
PDF
Datatypes in python
PPTX
Chapter 17 Tuples
PPTX
Python Exception Handling
PPTX
Python dictionary
PDF
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
List in Python
Python exception handling
Print input-presentation
Python programming : Classes objects
Stack and Queue
Basics of Object Oriented Programming in Python
structure and union
Conditional and control statement
Python Control structures
Python tuple
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Stacks in c++
Preprocessor directives in c language
Chapter 05 classes and objects
Datatypes in python
Chapter 17 Tuples
Python Exception Handling
Python dictionary
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Ad

Similar to Error and exception in python (20)

PDF
Unit 4-Exception Handling in Python.pdf
PPTX
Exception Handling in python programming.pptx
PDF
Python programming : Exceptions
PPT
Firoze_Errors_Exceptions in python__.ppt
DOCX
Exception handlingpdf
PPTX
Exception handling.pptx
PDF
lecs101.pdfgggggggggggggggggggddddddddddddb
PPT
Exception Handling on 22nd March 2022.ppt
PPTX
Exception Handling.pptx
PPTX
Exception Handling in Python Programming.pptx
PPTX
Exception Handling in Python programming.pptx
PPTX
Download Wondershare Filmora Crack Latest 2025
PPTX
Adobe Photoshop 2025 Cracked Latest Version
PPTX
FL Studio Producer Edition Crack 24 + Latest Version [2025]
PPTX
Exception handling with python class 12.pptx
PPTX
Python Lecture 7
PPT
Exception handling in python and how to handle it
PPT
Exception Handling using Python Libraries
PPTX
exceptioninpython.pptx
Unit 4-Exception Handling in Python.pdf
Exception Handling in python programming.pptx
Python programming : Exceptions
Firoze_Errors_Exceptions in python__.ppt
Exception handlingpdf
Exception handling.pptx
lecs101.pdfgggggggggggggggggggddddddddddddb
Exception Handling on 22nd March 2022.ppt
Exception Handling.pptx
Exception Handling in Python Programming.pptx
Exception Handling in Python programming.pptx
Download Wondershare Filmora Crack Latest 2025
Adobe Photoshop 2025 Cracked Latest Version
FL Studio Producer Edition Crack 24 + Latest Version [2025]
Exception handling with python class 12.pptx
Python Lecture 7
Exception handling in python and how to handle it
Exception Handling using Python Libraries
exceptioninpython.pptx
Ad

More from junnubabu (12)

PPTX
Priority queue in DSA
PPTX
Data struchers and algorithms
PPTX
Multithreading in java
PPTX
Exceptions handling in java
PPTX
Mobile transport layer .
PPTX
Internet protocol (ip)
PPTX
Data pre processing
PPTX
TELECOMMUNICATIONS SYSTEMS
PPTX
MEDIUM ACCESS CONTROL
PPTX
WIRELESS TRANSMISSION
PPTX
MOBILE COMMUNICATION
PPTX
Location based reminder
Priority queue in DSA
Data struchers and algorithms
Multithreading in java
Exceptions handling in java
Mobile transport layer .
Internet protocol (ip)
Data pre processing
TELECOMMUNICATIONS SYSTEMS
MEDIUM ACCESS CONTROL
WIRELESS TRANSMISSION
MOBILE COMMUNICATION
Location based reminder

Recently uploaded (20)

PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
master seminar digital applications in india
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Business Ethics Teaching Materials for college
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PDF
Introduction-to-Social-Work-by-Leonora-Serafeca-De-Guzman-Group-2.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
master seminar digital applications in india
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
O7-L3 Supply Chain Operations - ICLT Program
PPH.pptx obstetrics and gynecology in nursing
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
01-Introduction-to-Information-Management.pdf
Week 4 Term 3 Study Techniques revisited.pptx
Open Quiz Monsoon Mind Game Prelims.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Business Ethics Teaching Materials for college
Abdominal Access Techniques with Prof. Dr. R K Mishra
Cardiovascular Pharmacology for pharmacy students.pptx
Introduction-to-Social-Work-by-Leonora-Serafeca-De-Guzman-Group-2.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Mark Klimek Lecture Notes_240423 revision books _173037.pdf

Error and exception in python

  • 1. UNIT-5 Python Programming Errors and Exceptions N.JUNNUBABU. ASST PROF.
  • 2. 5.Errors and Exceptions  There are two distinguishable kinds of errors: 1. syntax errors. 2. exceptions.  5.1.Syntax Errors:  Syntax errors, also known as parsing errors, are the most common kind of errors. Example:- while True print(‘python programming') SyntaxError: invalid syntax  The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected. in the example, the error is detected at the function print(), since a colon (':') is missing before it.
  • 3. 5.2.Exceptions  Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions. Example:- >>> 10 * (1/0) Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> 10 * (1/0) ZeroDivisionError: division by zero  The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions.
  • 4. 5.3.Handling an Exceptions  If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible. Syntax:-syntax of try....except...else blocks try: You do your operations here ...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block.
  • 5. Imp.. points above-mention syntax Note:-  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.  You can also provide a generic except clause, which handles any exception.  After the except clause(s), you can include an else-clause. The code in the else block executes if the code in the try: block does not raise an exception.  The else-block is a good place for code that does not need the try: block's protection.
  • 6. Try…except…example:  The try-except block is used to handle exceptions in python.  When an exception occurs, it is caught by the except block. The catch block cannot be used without the try block. def divide(num1, num2): try: result = num1 // num2 remainder = num1 % num2 except ZeroDivisionError: print("...You are dividing(divisor) by zero...") else: print("Your answer is(Gives only quotient):", result) print("Your answer is(Gives only remainder) :", remainder) num1=int(input("enter the num1(dividend) value:")) num2=int(input("enter the num2(divisor) value:")) divide(num1, num2)
  • 7. Continue.. Finally block:- You can use a finally: block along with a try: block. The finally: block is a place to put any code that must execute, whether the try: block raised an exception or not. Output:- enter the num1(dividend) value:128 enter the num2(divisor) value:14 Your answer is(Gives only quotient): 9 Your answer is(Gives only remainder) : 2 ........................................................................ enter the num1(dividend) value:120 enter the num2(divisor) value:0 ...You are dividing(divisor) by zero...
  • 8. Try-finally example. try: a=int(input("entere a value:")) b=int(input("entere b value:")) c=a//b except ZeroDivisionError: print("division can't possible:(b=0)") else: print("a//b value:",c) finally: print(".....enter of program.....") Output:- entere a value:10 entere b value:0 division can't possible:(b=0) .....enter of program..... entere a value:10 entere b value:2 a//b value: 5 .....enter of program.....
  • 9. 5.4.Raising an Exceptions  You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows Syntax:-raise [Exception [, args [, traceback]]] Example:- The sole argument to raise indicates the exception to be raised. If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments: raise ValueError # shorthand for 'raise ValueError()' raise NameError('HiThere') Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> raise NameError('HiThere') NameError: HiThere
  • 10. Example. The following example illustrates the use of raising an exception- #!/usr/bin/python3 def functionName( level ): if level <1: raise Exception(level) # The code below to this would not be executed # if we raise the exception return level try: l=functionName(-10) print ("level=",l) except Exception as e: print ("error in level argument",e.args[0]) Output:- error in level argument -10
  • 11. 5.5.Exception chaining  Exception chaining happens automatically when an exception is raised inside an except or finally section. Exception chaining can be disabled by using from None idiom: try: open('database.sqlite') except IOError: raise RuntimeError from None Traceback (most recent call last): File "<stdin>", line 4, in <module> RuntimeError
  • 12. 5.6.User - Defined Exceptions  Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions. Example:- class Error(Exception): """Base class for exceptions in this module.""" pass class InputError(Error): """Exception raised for errors in the input. Attributes: expression -- input expression in which the error occurred message -- explanation of the error """ def __init__(self, expression, message): self.expression = expression self.message = message class TransitionError(Error): """Raised when an operation attempts a state transition that's not allowed. Attributes: previous -- state at beginning of transition next -- attempted new state message -- explanation of why the specific transition is not allowed """ def __init__(self, previous, next, message): self.previous = previous self.next = next self.message = message
  • 13.  Most exceptions are defined with names that end in “Error”, similar to the naming of the standard exceptions.  Many standard modules define their own exceptions to report errors that may occur in functions they define. More information on classes is presented in chapter Classes. 5.7.Defining Clean-up Actions:-  The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example: try: raise KeyboardInterrupt finally: print('Goodbye, world!') Goodbye, world! KeyboardInterrupt Traceback (most recent call last): File "<stdin>", line 2, in <module>
  • 14.  If a finallyclause is present, the finally clause will execute as the last task before the try statement completes. The finally clause runs whether or not the try statement produces an exception.  For example:  the finally clause is executed in any event. In real world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful. def divide(x, y): try: result = x / y except ZeroDivisionError: print("division by zero!") else: print("result is", result) finally: print("executing finally clause") >>> divide(2, 1) result is 2.0 executing finally clause >>> divide(2, 0) division by zero! executing finally clause
  • 15. 5.8.Predefined Clean-up Actions  Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed.  The problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing. This is not an issue in simple scripts, but can be a problem for larger applications. The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.  After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines. Objects which, like files, provide predefined clean-up actions will indicate this in their documentation. for line in open("myfile.txt"): print(line, end="") with open("myfile.txt") as f: for line in f: print(line, end="")