PCEP Error Handling and Modules — Questions and Answers
Question 1: What is the purpose of a try-except block in Python?
- To handle exceptions and prevent program crashes (Correct answer)
- To create loops
- To define functions
- To import modules
Correct answer: To handle exceptions and prevent program crashes
Try-except blocks catch and handle exceptions that would otherwise terminate the program.
Question 2: What does the finally clause do in Python exception handling?
- Executes code regardless of whether an exception occurred (Correct answer)
- Only runs if an exception occurs
- Only runs if no exception occurs
- Prevents all exceptions
Correct answer: Executes code regardless of whether an exception occurred
The finally block always executes, making it ideal for cleanup operations.
Question 3: How do you import a specific function from a module in Python?
- from module import function (Correct answer)
- import function from module
- module.import(function)
- get function from module
Correct answer: from module import function
The from...import syntax allows importing specific names from a module.
Question 4: What is a Python package?
- A directory containing modules and an __init__.py file (Correct answer)
- A single Python file
- A built-in function
- A type of variable
Correct answer: A directory containing modules and an __init__.py file
Packages organize related modules in a directory structure with an __init__.py file.
Question 5: What exception is raised when dividing by zero in Python?
- ZeroDivisionError (Correct answer)
- ValueError
- TypeError
- ArithmeticError
Correct answer: ZeroDivisionError
Python raises ZeroDivisionError specifically for division by zero operations.
Question 6: What is the purpose of the raise statement in Python?
- To manually trigger an exception (Correct answer)
- To increase a variable value
- To elevate function priority
- To move code to a higher scope
Correct answer: To manually trigger an exception
The raise statement allows you to deliberately throw an exception in your code.
What is the purpose of a try-except block in Python?