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

Exceptionhandlingpdf__2025_04_03_09_11_48

The document provides an overview of exception handling in Python, explaining what exceptions are and how they can be managed using 'try', 'except', 'else', and 'finally' blocks. It lists various built-in exceptions such as IOError, ImportError, and ZeroDivisionError, and includes examples of how to implement exception handling in code. Additionally, it discusses user-defined exceptions and the use of the 'raise' statement to trigger exceptions intentionally.

Uploaded by

anjali.ezhava
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)
2 views21 pages

Exceptionhandlingpdf__2025_04_03_09_11_48

The document provides an overview of exception handling in Python, explaining what exceptions are and how they can be managed using 'try', 'except', 'else', and 'finally' blocks. It lists various built-in exceptions such as IOError, ImportError, and ZeroDivisionError, and includes examples of how to implement exception handling in code. Additionally, it discusses user-defined exceptions and the use of the 'raise' statement to trigger exceptions intentionally.

Uploaded by

anjali.ezhava
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/ 21

Exception

handling
 An exception is an error that happens during execution
of a program. When that error occurs, Python generates
an exception that can be handled, which avoids your pr
ogram to crash.

 Raising an exception breaks current code execution and


returns the exception back until it is handled.
Exception Errors
 IOError
If the file cannot be opened.

 ImportError
If python cannot find the module

 ValueError
Raised when a built-in operation or function receives an argument
that has the right type but an inappropriate value.
Exception Errors
 KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or
Delete)

 EOFError
Raised when one of the built-in functions (input() or raw_input())
hits an end-of-file condition (EOF) without reading any data

 Exception
Base class for all exceptions
 StopIteration
Raised when the next() method of an
iterator does not point to any object.

 SystemExit
Raised by the sys.exit() function.

 ArithmeticError
Base class for all errors that occur for
numeric calculation.
 OverflowError
Raised when a calculation exceeds maximum limit
for a numeric type.

 FloatingPointError
Raised when a floating point calculation fails.

 ZeroDivisionError
Raised when division or modulo by zero takes place
for all numeric types.

 AttributeError
Raised in case of failure of attribute reference or
assignment.
 IndexError
Raised when an index is not found in a sequence.

 KeyError
Raised when the specified key is not found in the dictionary.

 SyntaxError
Raised when there is an error in Python syntax.

 IndentationError
Raised when indentation is not specified properly.

 TypeError
Raised when an operation or function is attempted that is
invalid for the specified data type.
Set up exception handling
blocks
 The words "try" and "except" are Python
keywords and are used to catch exceptions.
 The code within the try clause will be executed
statement by statement.
 If an exception occurs, the rest of the try block
will be skipped and the except clause will be
executed.
 try:
 some statements here
 except:
 exception handling
Ex1:

try:
print (1/0)
except :
print ("You can't divide by zero, you're silly.")

Ex2:

try:
print (1/0)
except ZeroDivisionError:
print ("You can't divide by zero, you're silly.")
Ex1:

import sys
try:
number = int(input("Enter a numbers Only"))
except ValueError:
print ("sorry.. numbers only")
sys.exit()
print ("you entered number", number)

Ex2:

def this_fails():
x = 1/0
try:
this_fails()
except ZeroDivisionError as detail:
print ('Handling run-time error:', detail)
Try ... except ... else clause
 The else clause in a try , except statement must follow all
except clauses, and is useful for code that must be
executed if the try clause does not raise an exception.

try:
data = something_that_can_go_wrong
except IOError:
handle_the_exception_error
else:
doing_different_exception_handling
try:
a=10/0
print(a)
except ArithmeticError:
print("This statement is raising an exception")
else:
print("Welcome")
try:
f = open("1.txt", 'r')
except IOError:
print ('cannot open')
else:
print ("file has", len(f.readlines()), 'lines')
f.close()
try:
import foo
except ImportError as detail:
print ('Handling run-time error:', detail)
try:
fh= open("testfile","w")
fh.write("This is my test file for exception handling!!")
except IOError:
print("Error: can\'t find file or read data")
else:
print("Written content in the file successfully")
fh.close()
 In addition to using an except block after the try block,
you can also use the finally block.

 The code in the finally block will be executed regardless


of whether an exception occurs.

 Exceptions in the else clause are not handled by the


preceding except clauses.

 Make sure that the else clause is run before the finally
block.

 A finally clause is always executed before leaving the


try statement, whether an exception has occurred or
not.
Finally
try:
raise KeyboardInterrupt
finally:
print ('Goodbye, world!')
User-Defined Exceptions
 Custom Exception:
Creating your own Exception class or User Defined
Exceptions are known as Custom Exception.
class ErrorInCode(Exception):
def __init__(self, data):
self.data = data
def __str__(self):
return repr(self.data)
try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print ("Received error:", ae.data)
Raise an Exception
 raisewill cause an exception to occur and
thus execution control will stop in case it is not
handled.

 raise Exception_class
x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")

try:
a=10
print (a)
raise NameError("Hello")
except NameError as e:
print ("An exception occurred")
print (e)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy