Python Exception Handling





Exceptions are the errors that occurs during the time of code execution.

Before executing a code, interpreter will scan the code and will notify if any syntax error is present. Even though the syntax is correct, errors can happen during code execution, such errors are called as exceptions.

For example, in the below code python interpreter will not detect any syntax errors, but when the line “c= b / a” is executed, interpreter will throw an error because dividing by zero is not a valid operation.

	
a, b = 0, 1

c = b / a


---------Output---------

Traceback (most recent call last):
File "except.py", line 2, in module
c = b / a
ZeroDivisionError: division by zero


Some more examples:


a="hi"

b = int(a)
	
	
---------Output---------

Traceback (most recent call last):
File "except.py", line 2, in module
    b = int(a)
ValueError: invalid literal for int() with base 10: 'hi'



a = hello

---------Output---------

Traceback (most recent call last):
  File "except.py", line 1, in module
    a = hello
NameError: name 'hello' is not defined



a = "hello" + 5


---------Output---------


Traceback (most recent call last):
  File "except.py", line 1, in module
    a = "hello" + 5
TypeError: must be str, not int


	
fid = open ("abcd.txt", 'r')


---------Output---------

Traceback (most recent call last):
  File "except.py", line 1, in module
    fid = open ("abcd.txt", 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'abcd.txt'



Exeception Handling

Execption handling is the technique of catching errors to avoid unexpected ending of the script.

If you suspect that a code may raise an error during execution, you can catch that error by keeping that part of the code inside a “try” command.

For example if you want to handle the FileNotFoundError in the above code , try the following code

	
try:

	fid = open ("abcd.txt", 'r')

except FileNotFoundError:

	print ("File is not present, skipping the reading process...")

else:

	print (fid.read())

	fid.close()

Here interpreter will execute code given in the “try” block and if that raises a “FileNotFoundError” , the code mentioned in “except” block will get executed. If there is no error, code in the “else” block will get executed.

Note 1: These exeception names are built-in identifiers not keywords

Note 2: “else” clause is optional



Handling multiple exceptions:

If you want to catch multiple errors, you can use “except” clause with a tuple of error codes.

For example ,the following code will not work because “write” operation is not permitted when the file is open for reading. The except clause will catch the “IOError” and the mentioned error will be displayed.


try:
	
	fid = open ("abcd.txt", 'r')

	fid.write("hello world")

except (FileNotFoundError, IOError):

	print ("Error in opening file or writing ...")

else:

	fid.close()

You may also use multiple “except” clauses like in the example shown below


try:

	fid = open ("abcd.txt", 'r')

	fid.write("hello world")

except FileNotFoundError:

	print ("Error in opening file")

except IOError:

	print ("File opened successfully, but couldn't write")

else:

	fid.close()


Try with “Finally”

In some cases, you may want to excute a code even if try block is raising an error or not. You can use a “finally” clause for this.


fid = open ("abcd.txt", 'r')

try:

	fid.write("hello world")

except IOError:

	print ("Write operation: Failed")

else:

	print ("Write operation: Succeful")

finally:

	print ("Inside finally ...")

	fid.close()

In the above code, if you open the file in “r” mode, try block will raise an exception and if you open using “w” it will not raise exception. In both cases , the code inside the finally block will get executed.



User Defined Exceptions

You can create your own exceptions by defining a new class which derived from the builtin class “Exception”.

Syntax:


class MyInputError(Exception):

	pass

Note: You can create new exceptions by deriving directly from the class “Exception” or indirectly from any other subclass which has derived from the class “Exception”.


Raising an Exception:

After creating a new exception, you can use “raise” command to raise this exception when the event happens.

For example:


class MyInputError(Exception):

	pass

a = int(input ("enter a number"))

try:

	if a <= 0:
		raise MyInputError()

except myInputError:

	print ("Enter a number greater than 0")

else:

	for tmp in range(a): print (tmp)


Exception arguments:

You can include arguments when you are raising an exception, . These arguements can be passed to a variable used with “except” clause or otherwise it will displayed with if the exception is not handled by an “except” clause.

Example:

	
a = int(input ("Enter a number : "))

class MyInputError(Exception):

	pass

try:
	if a < 0:
		raise MyInputError("Input is less than 0")

	if a < 5:

	raise MyInputError("Input is less than 5")

except MyInputError as tmp:

	print (tmp)

else:

	for tmp in range(a): print (tmp)
	

---------Output---------


Enter a number : 3

Input is less than 5

Enter a number : -1

Input is less than 0




Python – Assert statement

Assert is used to check an expression and raise an error if the expression fails.

For example:

	
a = int(input("Enter a number"))
	
assert a > 0 , "Wrong Input"

for tmp in range(a): print (tmp)



In the above example , code wont break if your input is greater than 0 . If the input is zero or less than zero , you will get the following output.

Traceback (most recent call last):
assert a > 0 , "Wrong Input"
AssertionError: Wrong Input


Previous chapter:Python training : File Operations