Answer the question
In order to leave comments, you need to log in
How to properly handle exceptions in Java?
Hello dear toasters. I have questions about exception handling in Java. There is a Counter
class :
package com.vogella.ide.counter.util;
public class Counter {
public int count (int x){
// TODO check that x > 0 and <= 255
// if not throw a new RuntimeException
// Example for a RuntimeException:
// throw new RuntimeException("x should be between 1 and 255");
// TODO calculate the numbers from 1 to x
// for example if x is 5, calculate
// 1 + 2 + 3 + 4 + 5
// TODO return your calculated value
// instead of 0
return 0;
}
}
package com.vogella.ide.counter.main;
import com.vogella.ide.counter.util.Counter;
public class Tester {
public static void main(String[] args) {
Counter counter = new Counter();
int result = counter.count(5);
if (result == 15) {
System.out.println("Correct");
} else {
System.out.println("False");
}
try {
counter.count(256);
} catch (RuntimeException e) {
System.out.println("Works as exepected");
}
}
}
Answer the question
In order to leave comments, you need to log in
Yes, return will be superfluous. In such cases, they usually throw
throw new IllegalArgumentException("x should be between 1 and 255");
About the rest of the implementation, you need to ask the authors of such a task. Testing by counting 15 automatically is stupid, tests shouldn't repeat the implementation.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question