Python - Exceptions Handling: What Is Exception?
Python - Exceptions Handling: What Is Exception?
What is Exception?
An exception is an event, which occurs during the execution of a program
that disrupts the normal flow of the program's instructions. In general, when a
Python script encounters a situation that it cannot cope with, it raises an
exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
Handling an exception
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
try:
You do your operations here;
......................
except Exception I:
If there is ExceptionI, then execute this block.
except Exception II:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
finally :
This will execute in every case
Example-1
This example opens a file, writes content in the, file and comes out gracefully
because there is no problem at all −
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()
Output
Written content in the file successfully
Example2
This example tries to open a file where you do not have write permission, so it
raises an exception −
try:
fh = open("testfile", "r")
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")
Output Error: can't find file or read data
The try block lets you test a block of code for errors.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try-
and except blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message. These exceptions can be handled using
the try statement:
try:
print(x)
except:
print("An exception occurred")
Many/Multiple Exceptions
You can define as many exception blocks as you want, e.g. if you want to
execute a special block of code for a special kind of error:
Example-1
Print one message if the try block raises a NameError and another for
other errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Else You can use the else keyword to define a block of code to be executed if
no errors were raised:
Example
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")
Raise an exception
Example
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Example4
x = "hello"