Handling Exceptions: Try: Except Inbuilt Exception
Handling Exceptions: Try: Except Inbuilt Exception
Exception handling is done by try and catch block. Suspicious code that may raise an exception,
this kind of code will be placed in try block. A block of code which handles the exception is
placed in except block.
Caching Exceptions
1. try…except
2. try…except…inbuilt exception
3. try… except…else
4. try…except…else….finally
5. try.. except..except..
6. try…raise..except..
7. User – defined Exception
try - except
try:
Code that create exception
except:
Exception handling statement.
Program Output
try: Enter age:10
age=int(input("Enter age: ")) 10
print(age)
except: Enter age: a
print("Oops, Something went wrong") Oops, Something went wrong
try…except…inbuilt exception
try:
Code that create exception
except inbuilt exception:
Exception handling statement.
Program Output
try: Enter your age: 10
age=int(input(“Enter you age”)) 10
print(age)
except ValueError: Enter your age: a
print(“Please type a number”) Please type a number
try… except…else:
try:
Statements
except Exception:
If there is Exception, then execute this block.
else:
If there is no exception then execute this block.
Program Output
try: Enter age: six
age=int(input(“Enter age:”)) Please type a number
except ValueError:
print(“Please type a number”) Enter age:6
else 6
print(age)
try…except…else….finally
try:
Statements
except Exception:
If there is Exception, then execute this block.
else:
If there is no exception then execute this block.
Finally:
Statements to be executed always
Program Output
try: Enter your age: 10
age=int(input(“Enter you age”)) 10
except ValueError: Bye
print(“Please type a number”)
else: Enter your age: a
print(age) Please type a number
finally: Bye
print(“Bye”)
try.. except..except..
Method1 : Multiple Exceptions can be declared using the same except statement:
Syntax:
try:
Statements
except Exception1,Exception2,Exception3,..,ExceptionN :
execute this code in case any Exception of these occur.
else:
execute code in case no exception occurred.
Program Output
try: Enter a:10
a=int(input("Enter a: ")) Enter b: 0
b=int(input("Enter b: ")) Oops, Something went wrong
c=a/b
print(c) Enter a: 10
except (ValueError, ZeroDivisionError): Enter b: h
print("Oops, Something went wrong") Oops, Something went wrong
Method 2:
Syntax
try:
Code that create exception
except inbuilt exception:
Exception handling statement.
except inbuilt exception:
Exception handling statement.
Program Output
try: Enter a:10
a=int(input("Enter a: ")) Enter b: 0
b=int(input("Enter b: ")) can’t divide by zero
c=a/b
print(c) Enter a: 10
except (ValueError): Enter b: h
print("It’s not a number") It’s not a number
except ( ZeroDivisionError)
print(“can’t divide by zero”)
try…raise..except..
In python, exceptions are raised when corresponding errors occur at run time, but we can
forcefully raise it using the keyword raise.
Syntax
try:
………………
raise error_name
except inbuilt exception:
Exception handling statement.
Program Output
try: Enter age:6
age=int(input("enter your age:")) 6
if (age<0):
raise ValueError Enter age: -6
print(age) you have entered incorrect age
except ValueError:
print("you have entered incorrect age")
User-defined Exceptions:
Programmers may name their own exceptions by creating a new exception class. Exceptions
need to be derived from the Exception class, either directly or indirectly.
Example:
Program Output
class Error(Exception): Enter a number: 5
"Base class for other exceptions" This value is too small, try again!
pass
class ValueTooSmallError(Error): Enter a number: 15
This value is too large, try again!
"Raised when the input value is too small"
pass Enter a number: 10
class ValueTooLargeError(Error): Congratulations! You guessed it correctly.
"Raised when the input value is too large"
pass
number = 10
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.")
Format operator:
The write( ) accept only string as arguments. To give other values in write(), the values must be
converted to string.
Methods – 1 : str( )
The built-in function str() is used to convert other values to strings.
Program Output
f=open("file1.txt","w+") 100
f.write(str(100))
f.close()
f=open("file1.txt","r+")
str=f.read()
print(str)
f.close()
Program Output
f=open("file1.txt","w+") 150
x=150
f.write('%d'%x)
f.close()
f=open("file1.txt","r+")
str=f.read()
print(str)
f.close()
If there is more than one format sequence in the string, the second argument has to be a tuple.
Each format sequence is matched with an element of the tuple, in order.
Program Output
f=open("file1.txt","w+") Ram scored 9.1 GPA in sem 1
x=9.1
y='GPA'
z=1
f.write('Ram scored %g %s in sem
%d'%(x,y,z))
f.close()
f=open("file1.txt","r+")
str=f.read()
print(str)
f.close()
File Modes
Modes Description
r Opens a file for reading only.
If file exists, read
If not exist, shows error
The file pointer is placed at the beginning of the file. This is the default mode.
rb Opens a file for reading only in binary format.
If file exists, read
If not exist, shows error
The file pointer is placed at the beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing.
If file exists, read
If not exist, shows error
The file pointer placed at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format.
If file exists, read
If not exist, shows error
The file pointer placed at the beginning of the file.
w Opens a file for writing only.
If file exists, overwrite
If file not exist, create a file
wb Opens a file for writing only in binary format.
If file exists, overwrite
If file not exist, create a file
w+ Opens a file for both writing and reading.
If file exists, overwrite
If file not exist, create a file
wb+ Opens a file for both writing and reading in binary format.
If file exists, overwrite
If file not exist, create a file.
a Opens a file for appending.
If file exists, file pointer is at the end of the file for appending.
If file not exists, create a file
ab Opens a file for appending in binary format.
If file exists, file pointer is at the end of the file for appending.
If file not exists, create a file
a+ Opens a file for both appending and reading.
If file exists, file pointer is at the end of the file for appending.
If file not exists, create a file
ab+ Opens a file for both appending and reading in binary format.
If file exists, file pointer is at the end of the file for appending.
If file not exists, create a file
File Methods
Method Description
close() Close a file after it has been opened
read( ) Read the contents of the size
readable( ) Returns whether a file is readable or not
readline( ) Read only one line from file
readlines( ) Read all lines in the file as a list, where each line is an item.
write(‘string’) Write the specified string into the file
writable( ) Returns whether a file is readable or not
writelines([ list of strings] ) Write the list of lines into the file
seek( ) Change the current file position
seekable( ) Returns whether a file is seekable or not
tell( ) Return the current file position
truncate(size) Resize the file to the given specified size
Program Output
f=open("file1.txt","w+") Python is a programming language
f.write("Python is a programming language")
f.close()
f=open("file1.txt","r+")
str=f.read()
print(str)
f.close()