Computer Science
When are the following built-in exceptions raised? Give examples to support your answers.
- ImportError
- IOError
- NameError
- ZeroDivisionError
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
Related Questions
"Every syntax error is an exception but every exception cannot be a syntax error." Justify the statement.
What is the use of a raise statement? Write a code to accept two numbers and display the quotient. Appropriate exception should be raised if the user enters the second number (denominator) as zero (0).
Use assert statement in Question No. 3 to test the division expression in the program.
Define the following:
- Exception Handling
- Throwing an exception
- Catching an exception