SlideShare a Scribd company logo
Exception Handling
1) A Python programterminates as soon as it encounters an error.
2) In Python, an error can be a syntaxerror or logical errors and
exceptions.
3) When these exceptions occur, it causes the currentprocess to
stop and passes it to the calling process until it is handled.
4) If not handled, ourprogram will crash.
Sr.No. Exception Name & Description
1
Exception
Base class for all exceptions
2
StopIteration
Raised when the next() method of an iterator does not point to any object.
3
SystemExit
Raised by the sys.exit() function.
4
StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.
5
ArithmeticError
Base class for all errors that occur for numeric calculation.
6
OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.
7
FloatingPointError
Raised when a floating point calculation fails.
8
ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric types.
9
AssertionError
Raised in case of failure of the Assert statement.
10
AttributeError
Raised in case of failure of attribute reference or assignment.
11
EOFError
Raised when there is no input from either the raw_input() or input() function and the end of
file is reached.
12
ImportError
Raised when an import statement fails.
13
KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
14
LookupError
Base class for all lookup errors.
15
IndexError
Raised when an index is not found in a sequence.
16
KeyError
Raised when the specified key is not found in the dictionary.
17
NameError
Raised when an identifier is not found in the local or global namespace.
18
UnboundLocalError
Raised when trying to access a local variable in a function or method but no value has
been assigned to it.
19
EnvironmentError
Base class for all exceptions that occur outside the Python environment.
20
IOError
Raised when an input/ output operation fails, such as the print statement or the open()
function when trying to open a file that does not exist.
21
IOError
Raised for operating system-related errors.
22
SyntaxError
Raised when there is an error in Python syntax.
23
IndentationError
Raised when indentation is not specified properly.
24
SystemError
Raised when the interpreter finds an internal problem, but when this error is encountered
the Python interpreter does not exit.
25
SystemExit
Raised when Python interpreter is quit by using the sys.exit() function. If not handled in
the code, causes the interpreter to exit.
26
TypeError
Raised when an operation or function is attempted that is invalid for the specified data
type.
27
ValueError
Raised when the built-in function for a data type has the valid type of arguments, but the
arguments have invalid values specified.
28
RuntimeError
Raised when a generated error does not fall into any category.
29
NotImplementedError
Raised when an abstract method that needs to be implemented in an inherited class is not
actually implemented.
Detecting and HandlingExceptions
1.Exceptions can be detected by incorporating them as partof a try
statement.
2.Any code suite of a Try statement will be monitored for exceptions.
3.Thereare two main forms of the try statement:
try-except
try-finally.
4.Thesestatements are mutually exclusive, meaning that you pick
only one of them.
5.A try statement can be accompanied by one or more except
clauses, exactly one finally clause, or a hybrid try-except-finally
combination.
6.try-exceptstatements allow one to detect and handle exceptions.
7.Thereis even an optional else clause for situations where code
needs to run only when no exceptions aredetected
8.Meanwhile, try-finally statements allow only for detection and
processing of any obligatory cleanup, but otherwise haveno facility
in dealing with exceptions.
try:
print(x)
except:
print("An exception occurred")
Output:
An exception occurred
try Statement with Multiple excepts
You can define as manyexception blocks as you want,e.g. if you
want to execute a special block of code for a special kind of error:
try:
print(x)
except NameError:
print("Variablex is not defined")
except:
print("Something else went wrong")
Else:
n Python,using the else statement,you can instruct a program to
execute a certain block of code onlyin the absence of exceptions.
Raising an Exception:
We can use raiseto throw an exception if a condition occurs.
The statement can be complemented with a custom exception.
x = 10
if x > 5:
raise Exception('x should not exceed 5. The value of x was:
{}'.format(x))
Traceback (mostrecent call last):
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
File <“input”>, line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
The AssertionError Exception
Instead of waiting for a program to crash midway, you can also start
by making an assertion in Python.
We assertthat a certain condition is met.
If this condition turns out to be True, then that is excellent! The program
can continue.
If the condition turns out to be False, you can havethe program throw
an AssertionError exception.
import sys assert('linux'in sys.platform), "This coderuns on Linux
only."
Traceback (most recent call last):
File
, line 2, in <module>
import sys
assert ('linux' in sys.platform), "This code
runs on Linux only."
Finally:
The finally block, if specified, will be executed regardless if the try block
raises an error or not.
Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The'try except' is finished")
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
Catching Specific Exceptions in Python:
A try clause can have any number of except clause to handle them
differently but only one will be executed in casean exception occurs.
1.try:
2.# do something
3.pass
5.except ValueError:
6.# handle ValueError exception
7.pass
9.except (TypeError, ZeroDivisionError):
# handle multiple exceptions
11.#TypeError and ZeroDivisionError
12.pass
14.except:
15.#handle all other exceptions
16.pass
Exceptions as Strings:
1)Prior to Python 1.5, standard exceptions wereimplemented as strings.
2)However, this became limiting in that it did not allow for exceptions to
have relationships to each other.
3)With the advent of exception classes, this is no longer the case. As of
1.5, all standard exceptions are now classes.
4)Itis still possiblefor programmers to generate their own exceptions as
strings, butwe recommend using exception classes from now on.
5)For backward compatibility, it is possibleto revertto string-based
exceptions.
6)Starting the Python interpreter with the command-line option –X will
provideyou with the standard exceptions as strings.
7)This feature will be obsolete beginning with Python 1.6.
8)Python 2.5 begins the process of deprecating string exceptions from
Python forever.
9)In 2.5, raiseof string exceptions generates a warning.
10)In 2.6, thecatching of string exceptions results in a warning.
11)Sincethey are rarely used and are being deprecated
12)You may use an external or third party module, which may still have
string exceptions.
13)String exceptions are a bad idea anyway
Raising Exceptions
1)The interpreter was responsiblefor raising all of the exceptions we
have seen so far.
2)Theseexist as a result of encountering an error during execution.
3)A programmer writing an API may also wish to throw an exception on
erroneous input, for example, so Python provides a mechanism for the
programmer to explicitly generate an exception: the raisestatement.
Raise Statements
1.Syntaxand Common Usage
2.The raisestatement is quite flexible with the arguments it supports.
The general syntaxfor raise is:
raise [SomeException [, args [, traceback]]]
3.The firstargument, SomeException, is the name of the exception to
raise
4.If present, it musteither be a string, class, or instance .
5.SomeException must be given if any of the other arguments (args or
traceback) are present.
6.The second expression contains optional args (aka parameters, values)
for the exception.
7.This value is either a single objector a tuple of objects.
8.In mostcases, the single argumentconsists of a string indicating the
causeof the error.
9.When a tuple is given, it usually equates to an error string, an error
number, and perhaps an error location, such as a file, etc.
10.Thefinal argument, TRaceback, is also optional.
11.This third argument is usefulif you wantto reraisean exception.
12.Arguments thatare absentare represented by the value None.
Assertions
Assertions arediagnostic predicates that mustevaluate to Boolean true;
otherwise, an exception is raised to indicate that the expression is false.
assertStatement:
The assertstatement evaluates a Python expression, taking no action if
the assertion succeeds, butotherwiseraising an AssertionError
exception.
The syntax for assertis:
assert expression [, arguments]
>>> assert 1 == 0, 'One does notequalzero silly!‘
Traceback (innermostlast):
File "<stdin>", line 1, in ?
AssertionError: One doesnot equalzero silly!
Why exceptions(now)?
There is no doubt that errors will be around as long as softwareis
around.
Execution environments havechanged, and so has our need to adapt
error-handling.
The ability to handle errors moreimportant
users areno longer the only ones directly running applications.
As the Internetand online electronic commerce become more pervasive,
Web servers willbe the primary users of application software.
This means that applications cannot justfail or crash anymore, because
if they do, systemerrors translateto browser errors, and thesein turn
lead to frustrated users.
Losing eyeballs means losing revenue and potentially significant
amounts of irrecoverablebusiness.
Ad

More Related Content

What's hot (20)

Exception handling
Exception handlingException handling
Exception handling
Abishek Purushothaman
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
Hemant Chetwani
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
Vince Vo
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in c
Memo Yekem
 
Effective Java Second Edition
Effective Java Second EditionEffective Java Second Edition
Effective Java Second Edition
losalamos
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
junnubabu
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
junnubabu
 
3.C#
3.C#3.C#
3.C#
Raghu nath
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
yugandhar vadlamudi
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Chap12
Chap12Chap12
Chap12
Terry Yoast
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its Handling
Bharat17485
 
9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11
Terry Yoast
 
Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
Alpesh Oza
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
Lifna C.S
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Abhishek Pachisia
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
Hemant Chetwani
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
Vince Vo
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in c
Memo Yekem
 
Effective Java Second Edition
Effective Java Second EditionEffective Java Second Edition
Effective Java Second Edition
losalamos
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
junnubabu
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
junnubabu
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its Handling
Bharat17485
 
9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11
Terry Yoast
 
Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
Alpesh Oza
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
Lifna C.S
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 

Similar to Exception handlingpdf (20)

Java unit 11
Java unit 11Java unit 11
Java unit 11
Shipra Swati
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
Intro C# Book
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
SukhpreetSingh519414
 
Exception handling with python class 12.pptx
Exception handling with python class 12.pptxException handling with python class 12.pptx
Exception handling with python class 12.pptx
PreeTVithule1
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
Narayana Swamy
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
JAYAPRIYAR7
 
Exception Handling using Python Libraries
Exception Handling using Python LibrariesException Handling using Python Libraries
Exception Handling using Python Libraries
mmvrm
 
Exception handling in python and how to handle it
Exception handling in python and how to handle itException handling in python and how to handle it
Exception handling in python and how to handle it
s6901412
 
Exception Handling in Python Programming.pptx
Exception Handling in Python Programming.pptxException Handling in Python Programming.pptx
Exception Handling in Python Programming.pptx
vinayagrawal71
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.pptComputer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
ShafiEsa1
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
Megha V
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
Eduardo Bergavera
 
Exception handling and throw and throws keyword in java.pptx
Exception handling and throw and throws keyword in java.pptxException handling and throw and throws keyword in java.pptx
Exception handling and throw and throws keyword in java.pptx
shikhaverma566116
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
Intro C# Book
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Exception handling with python class 12.pptx
Exception handling with python class 12.pptxException handling with python class 12.pptx
Exception handling with python class 12.pptx
PreeTVithule1
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
JAYAPRIYAR7
 
Exception Handling using Python Libraries
Exception Handling using Python LibrariesException Handling using Python Libraries
Exception Handling using Python Libraries
mmvrm
 
Exception handling in python and how to handle it
Exception handling in python and how to handle itException handling in python and how to handle it
Exception handling in python and how to handle it
s6901412
 
Exception Handling in Python Programming.pptx
Exception Handling in Python Programming.pptxException Handling in Python Programming.pptx
Exception Handling in Python Programming.pptx
vinayagrawal71
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).pptJava Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.pptComputer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
ShafiEsa1
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
Megha V
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
Eduardo Bergavera
 
Exception handling and throw and throws keyword in java.pptx
Exception handling and throw and throws keyword in java.pptxException handling and throw and throws keyword in java.pptx
Exception handling and throw and throws keyword in java.pptx
shikhaverma566116
 
Ad

Recently uploaded (20)

SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Ad

Exception handlingpdf

  • 1. Exception Handling 1) A Python programterminates as soon as it encounters an error. 2) In Python, an error can be a syntaxerror or logical errors and exceptions. 3) When these exceptions occur, it causes the currentprocess to stop and passes it to the calling process until it is handled. 4) If not handled, ourprogram will crash. Sr.No. Exception Name & Description 1 Exception Base class for all exceptions 2 StopIteration Raised when the next() method of an iterator does not point to any object. 3 SystemExit Raised by the sys.exit() function. 4 StandardError Base class for all built-in exceptions except StopIteration and SystemExit. 5 ArithmeticError
  • 2. Base class for all errors that occur for numeric calculation. 6 OverflowError Raised when a calculation exceeds maximum limit for a numeric type. 7 FloatingPointError Raised when a floating point calculation fails. 8 ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types. 9 AssertionError Raised in case of failure of the Assert statement. 10 AttributeError Raised in case of failure of attribute reference or assignment. 11 EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached. 12 ImportError Raised when an import statement fails. 13 KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c. 14 LookupError Base class for all lookup errors. 15 IndexError Raised when an index is not found in a sequence. 16 KeyError Raised when the specified key is not found in the dictionary. 17 NameError
  • 3. Raised when an identifier is not found in the local or global namespace. 18 UnboundLocalError Raised when trying to access a local variable in a function or method but no value has been assigned to it. 19 EnvironmentError Base class for all exceptions that occur outside the Python environment. 20 IOError Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. 21 IOError Raised for operating system-related errors. 22 SyntaxError Raised when there is an error in Python syntax. 23 IndentationError Raised when indentation is not specified properly. 24 SystemError Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit. 25 SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit. 26 TypeError Raised when an operation or function is attempted that is invalid for the specified data type. 27 ValueError Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.
  • 4. 28 RuntimeError Raised when a generated error does not fall into any category. 29 NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented. Detecting and HandlingExceptions 1.Exceptions can be detected by incorporating them as partof a try statement. 2.Any code suite of a Try statement will be monitored for exceptions. 3.Thereare two main forms of the try statement: try-except try-finally. 4.Thesestatements are mutually exclusive, meaning that you pick only one of them. 5.A try statement can be accompanied by one or more except clauses, exactly one finally clause, or a hybrid try-except-finally combination. 6.try-exceptstatements allow one to detect and handle exceptions. 7.Thereis even an optional else clause for situations where code needs to run only when no exceptions aredetected 8.Meanwhile, try-finally statements allow only for detection and processing of any obligatory cleanup, but otherwise haveno facility in dealing with exceptions.
  • 5. try: print(x) except: print("An exception occurred") Output: An exception occurred try Statement with Multiple excepts You can define as manyexception blocks as you want,e.g. if you want to execute a special block of code for a special kind of error: try: print(x) except NameError: print("Variablex is not defined") except: print("Something else went wrong")
  • 6. Else: n Python,using the else statement,you can instruct a program to execute a certain block of code onlyin the absence of exceptions. Raising an Exception: We can use raiseto throw an exception if a condition occurs. The statement can be complemented with a custom exception. x = 10 if x > 5: raise Exception('x should not exceed 5. The value of x was: {}'.format(x)) Traceback (mostrecent call last): try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong")
  • 7. File <“input”>, line 4, in <module> Exception: x should not exceed 5. The value of x was: 10 The AssertionError Exception Instead of waiting for a program to crash midway, you can also start by making an assertion in Python. We assertthat a certain condition is met. If this condition turns out to be True, then that is excellent! The program can continue. If the condition turns out to be False, you can havethe program throw an AssertionError exception. import sys assert('linux'in sys.platform), "This coderuns on Linux only." Traceback (most recent call last): File , line 2, in <module> import sys assert ('linux' in sys.platform), "This code runs on Linux only."
  • 8. Finally: The finally block, if specified, will be executed regardless if the try block raises an error or not. Example
  • 9. try: print(x) except: print("Something went wrong") finally: print("The'try except' is finished") try: f = open("demofile.txt") f.write("Lorum Ipsum") except: print("Something went wrong when writing to the file") finally: f.close() Catching Specific Exceptions in Python: A try clause can have any number of except clause to handle them differently but only one will be executed in casean exception occurs. 1.try: 2.# do something
  • 10. 3.pass 5.except ValueError: 6.# handle ValueError exception 7.pass 9.except (TypeError, ZeroDivisionError): # handle multiple exceptions 11.#TypeError and ZeroDivisionError 12.pass 14.except: 15.#handle all other exceptions 16.pass Exceptions as Strings: 1)Prior to Python 1.5, standard exceptions wereimplemented as strings. 2)However, this became limiting in that it did not allow for exceptions to have relationships to each other. 3)With the advent of exception classes, this is no longer the case. As of 1.5, all standard exceptions are now classes. 4)Itis still possiblefor programmers to generate their own exceptions as strings, butwe recommend using exception classes from now on. 5)For backward compatibility, it is possibleto revertto string-based exceptions. 6)Starting the Python interpreter with the command-line option –X will provideyou with the standard exceptions as strings. 7)This feature will be obsolete beginning with Python 1.6. 8)Python 2.5 begins the process of deprecating string exceptions from Python forever.
  • 11. 9)In 2.5, raiseof string exceptions generates a warning. 10)In 2.6, thecatching of string exceptions results in a warning. 11)Sincethey are rarely used and are being deprecated 12)You may use an external or third party module, which may still have string exceptions. 13)String exceptions are a bad idea anyway Raising Exceptions 1)The interpreter was responsiblefor raising all of the exceptions we have seen so far. 2)Theseexist as a result of encountering an error during execution. 3)A programmer writing an API may also wish to throw an exception on erroneous input, for example, so Python provides a mechanism for the programmer to explicitly generate an exception: the raisestatement. Raise Statements 1.Syntaxand Common Usage 2.The raisestatement is quite flexible with the arguments it supports. The general syntaxfor raise is: raise [SomeException [, args [, traceback]]] 3.The firstargument, SomeException, is the name of the exception to raise 4.If present, it musteither be a string, class, or instance . 5.SomeException must be given if any of the other arguments (args or traceback) are present.
  • 12. 6.The second expression contains optional args (aka parameters, values) for the exception. 7.This value is either a single objector a tuple of objects. 8.In mostcases, the single argumentconsists of a string indicating the causeof the error. 9.When a tuple is given, it usually equates to an error string, an error number, and perhaps an error location, such as a file, etc. 10.Thefinal argument, TRaceback, is also optional. 11.This third argument is usefulif you wantto reraisean exception. 12.Arguments thatare absentare represented by the value None. Assertions Assertions arediagnostic predicates that mustevaluate to Boolean true; otherwise, an exception is raised to indicate that the expression is false. assertStatement: The assertstatement evaluates a Python expression, taking no action if the assertion succeeds, butotherwiseraising an AssertionError exception. The syntax for assertis: assert expression [, arguments] >>> assert 1 == 0, 'One does notequalzero silly!‘ Traceback (innermostlast): File "<stdin>", line 1, in ? AssertionError: One doesnot equalzero silly!
  • 13. Why exceptions(now)? There is no doubt that errors will be around as long as softwareis around. Execution environments havechanged, and so has our need to adapt error-handling. The ability to handle errors moreimportant users areno longer the only ones directly running applications. As the Internetand online electronic commerce become more pervasive, Web servers willbe the primary users of application software. This means that applications cannot justfail or crash anymore, because if they do, systemerrors translateto browser errors, and thesein turn lead to frustrated users. Losing eyeballs means losing revenue and potentially significant amounts of irrecoverablebusiness.