Note that there are some explanatory texts on larger screens.

plurals
  1. POJava unchecked/checked exception clarification
    primarykey
    data
    text
    <p>I've been reading about unchecked versus checked questions, none of the online resources have been truly clear about the difference and when to use both.</p> <p>From what I understand, both of them get thrown at runtime, both of them represent program states that are outside the expected bounds of the logic, but checked exceptions must be explicitly caught while unchecked ones do not.</p> <p>My question is, suppose for argument's sake I have a method that divides two numbers</p> <pre><code>double divide(double numerator, double denominator) { return numerator / denominator; } </code></pre> <p>and a method that requires divison somewhere</p> <pre><code>void foo() { double a = divide(b, c); } </code></pre> <p>Who is responsible for checking the case of the denominator being zero, and should an exception be checked or unchecked (ignoring Java's built in divison checks)?</p> <p>So, would the divide method be declared as is or as</p> <pre><code>double divide(double numerator, double denominator) throws DivideByZeroException { if(denominator == 0) throw DivideByZeroException else ... } void foo() { try{ double a = divide(b, c); } catch(DivideByZeroException e) {} } </code></pre> <p>or without a checked exception, as is:</p> <pre><code>double divide(double numerator, double denominator) { if(denominator == 0) throw DivideByZeroException else ... } void foo() { if(c != 0) double a = divide(b, c); } </code></pre> <p>and allow foo to make the divide by zero check?</p> <p>This problem originally arose in a mathematical program I wrote in which users entered numbers and logic classes performed calculations. I was never sure whether the GUI should check immediately for improper values, or whether the internal logic should catch them during calculation and throw exceptions.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload