Computer Science

When are the following built-in exceptions raised? Give examples to support your answers.

  1. ImportError
  2. IOError
  3. NameError
  4. ZeroDivisionError

Python Exception Handling

19 Likes

Answer

1. ImportError — It is raised when the requested module definition is not found.

Example :

import module
Output
ModuleNotFoundError: No module named 'module'

2. IOError — It is raised when the file specified in a program statement cannot be opened.

Example :

file = open("file1.txt", "r")
Output
FileNotFoundError: [Errno 2] No such file or directory: 'file1.txt'

3. NameError — It is raised when a local or global variable name is not defined.

Example :

print(var+40)
Output
NameError: name 'var' is not defined.

4. ZeroDivisionError — It is raised when the denominator in a division operation is zero.

Example :

print(50/0)
Output
ZeroDivisionError: division by zero

Answered By

8 Likes


Related Questions