Exceptionhandlingpdf__2025_04_03_09_11_48
Exceptionhandlingpdf__2025_04_03_09_11_48
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.
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.
Make sure that the else clause is run before the finally
block.
raise Exception_class
x = "hello"
try:
a=10
print (a)
raise NameError("Hello")
except NameError as e:
print ("An exception occurred")
print (e)