Python chapter 8 Exception handling in python

 


Welcome back.......!

In this chapter 8, we are going to learn exception handling in python. This is the last chapter of the python basic course, from the next chapter we will learn the advanced concepts and powerful libraries like pandas, NumPy,matplotib, seaborn, etc.

So let's get started......

Course content:

  • What is an exception?
  • Handling an exception.
  • The except clause with no exceptions.
  • The except clause with multiple exceptions.
  • The try-finally clause.
  • The argument of an exception.
  • Raising an exception.

What is an exception?
  • Python provides a very important feature to handle any unexpected error in your Python programs and to add debugging capabilities in them called 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 mmediately otherwise it terminates and quits.
Handling an exception
  • If we have some suspicious code that may raise an exception, we can defend our program by placing the suspicious code in a try: block.
  • After the try: block, include an except statement, followed by a block of code that handles the problem as elegantly as possible. 
  • Here is simple syntax of try....except...else blocks -
  • After the except clause(s), one can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.
  • The else-block is a good place for code that does not need the try: block's protection.
  • A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.
  • We can also provide a generic except clause, which handles any exception.

try:
You do your operations here
except ExceptionI:
If there is ExceptionI then execute this block.
except ExceptionII:
If there is ExceptionII then execute this block.
else:
if there is no exception then execute this block.

fh=open("example_read.txt","r")
fh.close()
Output=It will throw the error if the file is not there.
try:
fh=open("example_read.txt","r")
except IOError:
print("Error:can\'t find file or read file")
else:
print("The content is read successfully")
fh.close()
print("Normal exceution again")
Output=Error:can't find file or read file
Normal exceution again


try:
fh=open("example_read.txt","r")
print("Read content successfully")
x='ss'+3
print("Going to close the file")
fh.close()
except IOError:
print("Error:can\'t find file or read file")
except TypeError:
print("Type error generated")
Output=Error:can't find file or read file
The except clause with no exceptions
  • One can also use the except statement with no exceptions.
  • This kind of try-except statement catches all the exceptions that occur.
  • Using this kind of try-except statement is not considered in good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.

try:
fh=open("example_read.txt","r")
except IOError:
print("Error:can\'t find file or read file")
else:
print("The content is read successfully")
fh.close()
print("Normal exceution again")
Output=Error:can't find file or read file
Normal exceution again


The except clause with multiple exceptions
  • One can also use the same except statement to handle multiple exceptions 

try:
fh=open("example_1.txt","r")
print("Read content successfully")
x='ss'+3
print("Going to close the file")
fh.close()
except (IOError,TypeError):
print("We have exception")
else:
fh.close()
Output=We have exception

The try-finally clause
  • One can provide except clause with finally clause.
  • One can use the else clause as well along with the finally clause.
  • One can use the finally block along with a try block.
  • The finally block is a place to put any code that must execute, whether the try block raised an exception or not.
  • The syntax of the try-finally statement is this-

try:
fh=open("score.txt","r")
print("Read content successfully")
except IOError:
print("Error:can\'t find file or read file")
finally:
print("Done")
fh.close()
Output=Read content successfully
Done


try:
fh=open("score.txt","r")
try:
print("Read content successfully")
x='ss'+3
finally:
print("Going to close the file")
fh.close()
except IOError:
print("Error:can\'t find file or read file")
except TypeError:
print("Type error generated")
Output=Read content successfully
Going to close the file
Type error generated

Argument of an exception
  • An exception can have an argument, which is a value that gives additional information about the problem.
  • The contents of the argument vary by exception.
  • One capture an exception's argument by supplying a variable in the except clause.
  • If one writes the code to handle a single exception, one can have a variable follow the name of the exception in the except statement.
  • If we are trapping multiple exceptions, we can have a variable follow the tuple of the exception.
  • This variable receives the value of the exception mostly containing the cause of the exception.
  • The variable can receive a single value or multiple values in the form of a tuple
  • This tuple usually contains the error string, the error number, and an error location.

try:
fh=open("example_1.txt","r")
print("Read content successfully")
x='ss'+3
print("Going to close the file")
fh.close()
except (IOError,TypeError) as Argument:
print("We have exception---",Argument)
fh.close()
Output=We have exception--- [Errno 2] No such file or directory: 'example_1.txt'

def temp_convert(var):
return int(var)
temp_convert("xyz")
Output=Error-invalid literal for int() with base 10: 'xyz'

def temp_convert(var):
try:
return int(var)
except ValueError as Argument:
print("This argument is by exception handling the argument does not contain numbers",Argument)
temp_convert('xyz')
Output=This argument is by exception handling the argument does not contain numbers invalid literal for int() with base 10: 'xyz'
Raising an exception  
  • We can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows -
>>> raise [Exception [, args [, traceback]]]
  • Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument.
  • The argument is optional; if not supplied, the exception argument is None.
  • The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception.
  • An exception can be a string, a class, or an object.
  • Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows -
  • In order to catch an exception, an "except" clause must refer to the same exception thrown either as a class object or a simple string. 
  •  For example, to capture the above exception, we must write the except, the clause as follows -

def functionName(level):
if level is smaller than 1:Use the sign of smaller (level<1)
raise Exception (level)
return level
try:
x=functionName(-10)
print("Level =",x)
except Exception as e:
print("Error in level argument",e.args[0])
Output=Error in level argument -10

class MyError(Exception):
pass
def functionName(level):
if level is smller than 1: Use the sign of smaller (level<1)
raise Exception (level)
return level
try:
x=functionName(-10)
print("Level =",x)
except Exception as e:
print("Error in level argument",e.args[0])
Output=Error in level argument -10

Summary
  • We have implemented Handling an exception
  • We tried with The except Clause with No Exceptions and The except Clause with Multiple Exceptions
  • Also tried with The try-finally Clause, Argument of an Exception, and Raising an Exception.
So I hope that you have understood this topic, read carefully if you face any error comment below.
See you soon......
Best regards from,

msbtenote:)

THANK YOU!

Comments