top

Search

Python Tutorial

Most of the times, Python program encounters error because of violation of syntax in language keywords. Python interpreter immediately reports it usually along with the reason.>>> print "hello" SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello")?In Python 3.x, print is a built-in function and requires parentheses. The statement violates this usage and hence syntax error is displayed.Shown below is a definition of myfunction. First two statements inside the function are syntactically correct but the interpreter still flashes syntax error message immediately on encountering incorrect statement, without executing earlier  correct statements. Enter following code as test.py and try to run it from command line.def myfunction():        print ("hello")        x=10        y=2x myfunction() C:\python37>python test.py  File "test.py", line 4    y=2x       ^ SyntaxError: invalid syntaxMany a times though, program results in an error after it is run even if it doesn’t have any syntax error. Such an error is a runtime error called as exception. Python has a Exception class and a number of built-in exceptions are defined in Python library. Look at following snippets:IndexErrorIt is shown when trying to access item at invalid index.>>> numbers=[10,20,30,40] >>> for n in range(5):        print (numbers[n]) 10 20 30 40 Traceback (most recent call last):  File "<pyshell#2>", line 2, in <module>    print (numbers[n]) IndexError: list index out of rangeModuleNotFoundErrorThis is displayed when module could not be found.>>> import notamodule Traceback (most recent call last):  File "<pyshell#10>", line 1, in <module>    import notamodule ModuleNotFoundError: No module named 'notamodule'KeyErrorIt occurs as dictionary key is not found.>>> D1={'1':"aa", '2':"bb", '3':"cc"} >>> D1['4'] Traceback (most recent call last):  File "<pyshell#15>", line 1, in <module>    D1['4'] KeyError: '4'ImportErrorIt is shown when specified function is not available for import.>>> from math import cube Traceback (most recent call last):  File "<pyshell#16>", line 1, in <module>    from math import cube ImportError: cannot import name 'cube'StopIterationThis error appears when next() function is called after iterator stream exhausts.>>> it=iter([1,2,3]) >>> next(it) 1 >>> next(it) 2 >>> next(it) 3 >>> next(it) Traceback (most recent call last):  File "<pyshell#23>", line 1, in <module>    next(it) StopIterationTypeErrorThis is shown when operator or function is applied to an object of inappropriate type.>>> '2'+2 Traceback (most recent call last):  File "<pyshell#24>", line 1, in <module>    '2'+2 TypeError: must be str, not intValueErrorIt is displayed when function’s argument is of inappropriate type.>>> int('xyz') Traceback (most recent call last):  File "<pyshell#4>", line 1, in <module>    int('xyz') ValueError: invalid literal for int() with base 10: 'xyz'NameErrorThis is encountered when object could not be found.>>> age Traceback (most recent call last):  File "<pyshell#6>", line 1, in <module>    age NameError: name 'age' is not definedZeroDivisionErrorIt is shown when second operator in division is zero.>>> x=100/0 Traceback (most recent call last):  File "<pyshell#8>", line 1, in <module>    x=100/0 ZeroDivisionError: division by zeroKeyboardInterruptWhen user hits the interrupt key normally Control-C during execution of program.>>> name=input('enter your name') enter your name^c Traceback (most recent call last):  File "<pyshell#9>", line 1, in <module>    name=input('enter your name') KeyboardInterrupttry and catch keywordsAs the word 'exception' suggests, exception in code doesn't occur because of syntax error due to rare and exceptional situations it encounters during execution. More often than not the factors external to the program cause the exception. For example, incorrect input or malfunction IO device etc. Exception results in abrupt termination of program. It may damage system resources such as files becoming inaccessible etc. Hence the exceptions should be properly handled so as to prevent abrupt termination of program.Two keywords -  try and except - perform exception handling.The try: block contains statements which are susceptible for exception. In other words, you want interpreter to check whether it encounters exception in this block. If block is executed without exception, the except: block (which must appear immediately after try block) is skipped.If there occurs some exception, remaining statements in try block are abandoned and program jumps to except: block. Purpose of except: block is to take appropriate action regarding the cause of exception appropriately. For example printing appropriate error message, closing files if any are opened before exception etc.You can mention any type of built-in exception in front of except keyword. Subsequent block will be executed only if specified exception occurs.Statements after except block will be executed, irrespective of exception encountered or not.Following code has a dictionary containing name as key and marks as value. User is asked to input name and corresponding marks are displayed. If name input by user is not present, KeyError will occur which is handled by except clause as shown:marks={'Meena':50, 'Tina':60,'Leena':70} name=input("enter name:") try:        print ('marks:',marks[name]) except KeyError:        print ('name {} not in the list'.format(name)) print ("end of program")Two run cases of above program are shown below. One with input name in the list, and other not in the list.Output:enter name:Meena marks: 50 end of program enter name:Beena name Beena not in the list end of programAlso there may be multiple except blocks for different exceptions for a single try block. Of course, if type of exception doesn’t match with any of except blocks, it will remain unhandled and program will terminate. Following example uses two except blocks to process two different exception types:a=[10,20,30,40,50] try:        x=int(input('enter index: '))        print ('number at index {} is {}'.format(x,a[x])) except IndexError:        print ("index is out of range") except ValueError:        print ("index should be an integer")Output:enter index: 4 number at index 4 is 50 enter index: 7 index is out of range enter index: aa index should be an integerelse and finallyIn Python, else and finally keywords can also be used along with try and except clauses. While the except block is executed if exception occurs inside try block, the else block gets processed if try block is found to be free from exception.try:        #statements in try block except :        #executed when exception in try block else:        #executed if try block has no exceptionThe finally block will be processed regardless of exception occurs in try block or not. When there is no exception in try block,  except clause is skipped and program control enters else block and goes on to execute statements in finally block. If however, there’s an exception in try block, the corresponding except block will be processed, then statements in finally block will be processed.The example below demonstrates uses else and finally blocks. Variable x is initialized before try block. Inside try block, an input statement tries to change its value. If however, you try to input a non-numeric value, ValueError is raised. Program goes on to enter finally block and reset x to 0.On the other hand, valid value entered will update x. The else block prints it, and then finally block resets it to 0.x=0 try:    x=int(input("enter number: ")) except ValueError:    print("ValueError raised") else:    print(x) finally:    x=0    print ("reset x to ",x )Output:enter number: 11 11 reset x to  0 enter number: aa ValueError raised reset x to  0The finally block is typically employed to perform some kind of cleaning up operations in a process. For example you must close a file irrespective of errors in read/write operations.raise keywordPython's built-in errors are raised implicitly. The raise keyword is used to be generate exception explicitly.Following code accepts a number from user. The try block raises an exception if the number is outside the allowed range.try:        x=int(input('enter a number: '))        if x not in range(1,101):                raise Exception(x) except:        print (x, "is out of allowed range") else:        print (x, "is within the allowed range")Output:enter a number: 200 200 is out of allowed range enter a number: 50 50 is within the allowed rangeHere, Exception is not of any built-in type hence Except clause doesn't have any object .assert statementThe assert keyword checks whether given expression is true or false. Program execution terminates if it is false by raising AssertionError and proceeds only if the expression is true. Following code shows usage of assert statementnum=int(input('enter marks [out of 100] : ')) assert num>=0 and num<=100 print ('marks obtained: ', num)The print statement will display only if entered number is between 0 and 100 (both included). Any other number results in aborting the program after showing AssertionError.enter marks [out of 100] : 75 marks obtained:  75 enter marks [out of 100] : 125 Traceback (most recent call last):  File "C:\python36\assert.py", line 2, in <module>    assert num>=0 and num<=100 AssertionErrorTo display custom error message, put a string after the expression in assert statement as follows:num=int(input('enter marks [out of 100] : ')) assert num>=0 and num<=100, "only numbers in 0-100 accepted" print ('marks obtained: ', num)Output:enter marks [out of 100] : 125 Traceback (most recent call last):  File "C:\python36\assert.py", line 2, in <module>    assert num>=0 and num<=100, "only numbers in 0-100 accepted" AssertionError: only numbers in 0-100 acceptedThe AssertionError is also a built-in exception. So it can be used as argument in except block. When input causes AssertionError exception, it will be handled by except block. The except block treats string in assert statement goes as exception object.
logo

Python Tutorial

Python - Exceptions

Most of the times, Python program encounters error because of violation of syntax in language keywords. Python interpreter immediately reports it usually along with the reason.

>>> print "hello"
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello")?

In Python 3.x, print is a built-in function and requires parentheses. The statement violates this usage and hence syntax error is displayed.

Shown below is a definition of myfunction. First two statements inside the function are syntactically correct but the interpreter still flashes syntax error message immediately on encountering incorrect statement, without executing earlier  correct statements. Enter following code as test.py and try to run it from command line.

def myfunction():
       print ("hello")
       x=10
       y=2x
myfunction()
C:\python37>python test.py
 File "test.py", line 4
   y=2x
      ^
SyntaxError: invalid syntax

Many a times though, program results in an error after it is run even if it doesn’t have any syntax error. Such an error is a runtime error called as exception. Python has a Exception class and a number of built-in exceptions are defined in Python library. Look at following snippets:

IndexError

It is shown when trying to access item at invalid index.

>>> numbers=[10,20,30,40]
>>> for n in range(5):
       print (numbers[n])
10
20
30
40
Traceback (most recent call last):
 File "<pyshell#2>", line 2, in <module>
   print (numbers[n])
IndexError: list index out of range

ModuleNotFoundError

This is displayed when module could not be found.

>>> import notamodule
Traceback (most recent call last):
 File "<pyshell#10>", line 1, in <module>
   import notamodule
ModuleNotFoundError: No module named 'notamodule'

KeyError

It occurs as dictionary key is not found.

>>> D1={'1':"aa", '2':"bb", '3':"cc"}
>>> D1['4']
Traceback (most recent call last):
 File "<pyshell#15>", line 1, in <module>
   D1['4']
KeyError: '4'

ImportError

It is shown when specified function is not available for import.

>>> from math import cube
Traceback (most recent call last):
 File "<pyshell#16>", line 1, in <module>
   from math import cube
ImportError: cannot import name 'cube'

StopIteration

This error appears when next() function is called after iterator stream exhausts.

>>> it=iter([1,2,3])
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
 File "<pyshell#23>", line 1, in <module>
   next(it)
StopIteration

TypeError

This is shown when operator or function is applied to an object of inappropriate type.

>>> '2'+2
Traceback (most recent call last):
 File "<pyshell#24>", line 1, in <module>
   '2'+2
TypeError: must be str, not int

ValueError

It is displayed when function’s argument is of inappropriate type.

>>> int('xyz')
Traceback (most recent call last):
 File "<pyshell#4>", line 1, in <module>
   int('xyz')
ValueError: invalid literal for int() with base 10: 'xyz'

NameError

This is encountered when object could not be found.

>>> age
Traceback (most recent call last):
 File "<pyshell#6>", line 1, in <module>
   age
NameError: name 'age' is not defined

ZeroDivisionError

It is shown when second operator in division is zero.

>>> x=100/0
Traceback (most recent call last):
 File "<pyshell#8>", line 1, in <module>
   x=100/0
ZeroDivisionError: division by zero

KeyboardInterrupt

When user hits the interrupt key normally Control-C during execution of program.

>>> name=input('enter your name')
enter your name^c
Traceback (most recent call last):
 File "<pyshell#9>", line 1, in <module>
   name=input('enter your name')
KeyboardInterrupt

try and catch keywords

As the word 'exception' suggests, exception in code doesn't occur because of syntax error due to rare and exceptional situations it encounters during execution. More often than not the factors external to the program cause the exception. For example, incorrect input or malfunction IO device etc. Exception results in abrupt termination of program. It may damage system resources such as files becoming inaccessible etc. Hence the exceptions should be properly handled so as to prevent abrupt termination of program.

Two keywords -  try and except - perform exception handling.

The try: block contains statements which are susceptible for exception. In other words, you want interpreter to check whether it encounters exception in this block. If block is executed without exception, the except: block (which must appear immediately after try block) is skipped.

If there occurs some exception, remaining statements in try block are abandoned and program jumps to except: block. Purpose of except: block is to take appropriate action regarding the cause of exception appropriately. For example printing appropriate error message, closing files if any are opened before exception etc.

You can mention any type of built-in exception in front of except keyword. Subsequent block will be executed only if specified exception occurs.

Statements after except block will be executed, irrespective of exception encountered or not.

Following code has a dictionary containing name as key and marks as value. User is asked to input name and corresponding marks are displayed. If name input by user is not present, KeyError will occur which is handled by except clause as shown:

marks={'Meena':50, 'Tina':60,'Leena':70}
name=input("enter name:")
try:
       print ('marks:',marks[name])
except KeyError:
       print ('name {} not in the list'.format(name))
print ("end of program")

Two run cases of above program are shown below. One with input name in the list, and other not in the list.

Output:

enter name:Meena
marks: 50
end of program
enter name:Beena
name Beena not in the list
end of program

Also there may be multiple except blocks for different exceptions for a single try block. Of course, if type of exception doesn’t match with any of except blocks, it will remain unhandled and program will terminate. Following example uses two except blocks to process two different exception types:

a=[10,20,30,40,50]
try:
       x=int(input('enter index: '))
       print ('number at index {} is {}'.format(x,a[x]))
except IndexError:
       print ("index is out of range")
except ValueError:
       print ("index should be an integer")

Output:

enter index: 4
number at index 4 is 50
enter index: 7
index is out of range
enter index: aa
index should be an integer

else and finally

In Python, else and finally keywords can also be used along with try and except clauses. While the except block is executed if exception occurs inside try block, the else block gets processed if try block is found to be free from exception.

try:
       #statements in try block
except :
       #executed when exception in try block
else:
       #executed if try block has no exception

The finally block will be processed regardless of exception occurs in try block or not. When there is no exception in try block,  except clause is skipped and program control enters else block and goes on to execute statements in finally block. If however, there’s an exception in try block, the corresponding except block will be processed, then statements in finally block will be processed.

The example below demonstrates uses else and finally blocks. Variable x is initialized before try block. Inside try block, an input statement tries to change its value. If however, you try to input a non-numeric value, ValueError is raised. Program goes on to enter finally block and reset x to 0.

On the other hand, valid value entered will update x. The else block prints it, and then finally block resets it to 0.

x=0
try:
   x=int(input("enter number: "))
except ValueError:
   print("ValueError raised")
else:
   print(x)
finally:
   x=0
   print ("reset x to ",x )

Output:

enter number: 11
11
reset x to  0
enter number: aa
ValueError raised
reset x to  0

The finally block is typically employed to perform some kind of cleaning up operations in a process. For example you must close a file irrespective of errors in read/write operations.

raise keyword

Python's built-in errors are raised implicitly. The raise keyword is used to be generate exception explicitly.

Following code accepts a number from user. The try block raises an exception if the number is outside the allowed range.

try:
       x=int(input('enter a number: '))
       if x not in range(1,101):
               raise Exception(x)
except:
       print (x, "is out of allowed range")
else:
       print (x, "is within the allowed range")

Output:

enter a number: 200
200 is out of allowed range
enter a number: 50
50 is within the allowed range

Here, Exception is not of any built-in type hence Except clause doesn't have any object .

assert statement

The assert keyword checks whether given expression is true or false. Program execution terminates if it is false by raising AssertionError and proceeds only if the expression is true. Following code shows usage of assert statement

num=int(input('enter marks [out of 100] : '))
assert num>=0 and num<=100
print ('marks obtained: ', num)

The print statement will display only if entered number is between 0 and 100 (both included). Any other number results in aborting the program after showing AssertionError.

enter marks [out of 100] : 75
marks obtained:  75
enter marks [out of 100] : 125
Traceback (most recent call last):
 File "C:\python36\assert.py", line 2, in <module>
   assert num>=0 and num<=100
AssertionError

To display custom error message, put a string after the expression in assert statement as follows:

num=int(input('enter marks [out of 100] : '))
assert num>=0 and num<=100, "only numbers in 0-100 accepted"
print ('marks obtained: ', num)

Output:

enter marks [out of 100] : 125
Traceback (most recent call last):
 File "C:\python36\assert.py", line 2, in <module>
   assert num>=0 and num<=100, "only numbers in 0-100 accepted"
AssertionError: only numbers in 0-100 accepted

The AssertionError is also a built-in exception. So it can be used as argument in except block. When input causes AssertionError exception, it will be handled by except block. The except block treats string in assert statement goes as exception object.

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

Eula

This is my first time here. I am truly impressed to read all this in one place.

Jaypee Dela Cruz

Thank you for your wonderful codes and website, you helped me a lot especially in this socket module. Thank you again!

lucky verma

Thank you for taking the time to share your knowledge about using python to find the path! Your insight and guidance is greatly appreciated.

Pre Engineered Metal Building

Usually I by no means touch upon blogs however your article is so convincing that I by no means prevent myself to mention it here.

Pre Engineered Metal Building

Usually, I never touch upon blogs; however, your article is so convincing that I could not prevent myself from mentioning how nice it is written.

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses the .Net Framework. It utilizes the Common Language Interface (CLI) that describes the executable code as well as the runtime environment. C# can be used for various applications such as web applications, distributed applications, database applications, window applications etc.For greater understanding of this tutorial, a basic knowledge of object-oriented languages such as C++, Java etc. would be beneficial.
C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses ...

Read More