Project: Error-Handled Calculator
Project: Error-Handled Calculator
In this comprehensive chapter project, we will apply every concept covered across our exception handling module—Built-in Exceptions, try-except-else-finally, Explicit raise, and Custom Exception Hierarchies—to build a production-grade, crash-resilient Command-Line Scientific Calculator.
1. Project Specifications & Requirements
A naive calculator quickly crashes when a user supplies zero as a denominator, attempts to calculate the square root of a negative number, or enters non-numeric input. Our professional calculator meets the following engineering specifications:
- 1Custom Exception Hierarchy: Categorizes calculator errors (
InvalidOperatorError,MathDomainError,DivisionByZeroCalcError). - 2Safe Expression Tokenization: Safely parses user strings into operands and operators without using hazardous
eval(). - 3Advanced Operations: Supports basic arithmetic (
+,-,*,/,%), exponentiation (^), square roots (sqrt), and natural logarithms (log). - 4Resilient User Experience: Never crashes on invalid inputs or system interrupts like
KeyboardInterrupt(Ctrl+C). - 5Session Audit History: Stores previous calculations in memory for audit reporting.
2. Complete Calculator Code
3. Sample Execution Simulation
Multiple Choice Questions
1. In this project, why does the calculator avoid using Python's built-in eval() function?
A. eval() cannot perform floating point division B. eval() introduces serious arbitrary code execution security risks and uncontrolled exceptions C. eval() is removed in Python 3 D. eval() cannot parse spaces Answer: B Explanation: eval() executes arbitrary code supplied by the user, creating security vulnerabilities and making error handling unpredictable. Parsing tokens explicitly is much safer.
2. How does the CLI loop handle KeyboardInterrupt when a user presses Ctrl+C?
A. The script terminates with an unhandled traceback B. It intercepts KeyboardInterrupt and displays a polite message without terminating the application C. It resets the computer's terminal emulator D. It saves the session to disk and restarts the operating system Answer: B Explanation: By wrapping the input cycle in a try block that catches KeyboardInterrupt, the program handles user interrupts cleanly without crashing.
3. What exception is raised if the user inputs sqrt -9?
A. ZeroDivisionError B. MathDomainError C. IndexError D. SyntaxError Answer: B Explanation: Square roots of negative numbers are undefined in the real number system, triggering our custom MathDomainError.
4. Why is except CalculatorError able to catch both InvalidOperatorError and DivisionByZeroCalcError?
A. Because they are imported from math B. Because both classes inherit from CalculatorError C. Because Python checks variable names phonetically D. Because the else block converts them Answer: B Explanation: In Python's object-oriented exception model, catching a base class catches all instances of subclasses derived from it.
5. In which block is print(f"=> Result: {result:,.4f}") placed so that it never executes if an error occurred?
A. except B. finally C. else D. catch Answer: C Explanation: The else block executes only if the preceding try block completes successfully without raising any exceptions.
Understanding Iterators
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Creating Custom Exceptions | Understanding Iterators |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.