Explain the difference between a checked exception and an unchecked exception. B
ID: 654596 • Letter: E
Question
Explain the difference between a checked exception and an unchecked exception. Be detailed Suppose you are designing a method for a Car class that will deduct a given volume of gasoline from an instance variable that stores the amount of gas remaining in the tank. You want to create a custom exception class for this method. You want to make sure that the amount of gasoline to be deducted is not a negative number. Should your custom exception class inherit from a checked exception or an unchecked exception and why?Explanation / Answer
Difference between checked exception and unchecked exception:
A checked exception is any subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked.
With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.