[go: up one dir, main page]

0% found this document useful (0 votes)
22 views4 pages

Python - Exceptions Handling: What Is Exception?

Uploaded by

shreyasinghchamp
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)
22 views4 pages

Python - Exceptions Handling: What Is Exception?

Uploaded by

shreyasinghchamp
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/ 4

Python - Exceptions Handling

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

Python Try Except

 The try block lets you test a block of code for errors.

 The except block lets you handle the error.

 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:

The try block will generate an exception, because x is not defined:

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")

Finally : The finally block, if specified, will be executed regardless if the


try block raises an error or not.
Example-2
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Example-3

Try to open and write to a file that is not writable:

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

As a Python developer you can choose to throw an exception if a condition


occurs. To throw (or raise) an exception, use the raise keyword.

Example

Raise an error and stop the program if x is lower than 0:

x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Example4

Raise a TypeError if x is not an integer:

x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")

You might also like