Reputation: 47
Is there a way to throw an exception in your function without using an if statement in Java? For example, if an integer is smaller than 0, I want to throw an exception, but when checking that specific condition, I don't want to use an if(or switch) statement.
Upvotes: 1
Views: 5814
Reputation: 263
There is a generic simple implementation by Spring framework:
import org.springframework.util.Assert;
Assert.isTrue(someCondition,"some condition is not true.");
The implementation:
public static void isTrue(boolean expression, String message) {
if (!expression) {
throw new IllegalArgumentException(message);
}
}
Upvotes: 0
Reputation: 176
I assume you meant it like:
-Register integers once
-Throw exception when one of these integers turn 0
Wrote this class for that problem:
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
class IntegerChecker {
private ArrayList<AtomicInteger> list = new ArrayList<>();
IntegerChecker() {
Thread t = new Thread(() -> {
AtomicBoolean error = new AtomicBoolean(false);
while (!error.get()) {
list.forEach(integer -> {
if (integer.get() == 0) {
error.set(true);
throw new RuntimeException();
}
});
}
});
t.start();
}
void addInt(AtomicInteger i) {
list.add(i);
}
}
To test it use this small program with a JFrame:
public static void main(String[] args) {
AtomicInteger i = new AtomicInteger(5);
IntegerChecker checker = new IntegerChecker();
checker.addInt(i);
JFrame frame = new JFrame();
JButton button = new JButton("Click me to throw exception");
button.addActionListener(e -> i.set(0)); //If you click the button, the integer will turn to 0 which triggers the other class
frame.getContentPane().add(button);
frame.pack();
frame.setVisible(true);
}
(Could be that I interpreted a bit too much into the post, but I don't see a reason for asking a question like this if you don't mean it the way I thought of)
Upvotes: 1
Reputation: 16930
You could do a trick with ternary operator however this works like if-statement:
public class Task3 {
public static void main(String[] args) throws Exception {
someMethodReturningString(false);
}
private static String someMethodReturningString(boolean condition) throws Exception {
return condition ? "true" : methodThrowingException();
}
private static String methodThrowingException() throws Exception {
throw new Exception("Exception");
}
}
However it's just a trick. You cannot use throw keyword directly in tenary operator because tenary operator should always return a value. But you can always call methods that return required type in tenary operator.
I don't really know when you would need something like this. I think that if-else construction is best because you often want to throw exceptions "if" something is wrong or some "condition" is met.
Upvotes: 1
Reputation: 236122
You can do it, of course, but why?
public static void checkNegative(int n) {
try {
int[] a = new int[n];
} catch (NegativeArraySizeException e) {
throw new IllegalArgumentException();
}
}
The above method will throw an IllegalArgumentException
(or any other exception that you want) if n < 0
, and will do nothing if 0 <= n < 2^31 - 1
. But surely, somewhere in the code that creates an array there will be an if
, it's implicit.
Also you can use an assert
to ckeck a condition, which will throw an AssertionError
if the verified expression is false
- as long as assertions are enabled:
assert n >= 0;
And of course, you can throw an exception without explicitly verifying a condition, but most of the time you want to check something before throwing an exception.
public static void throwForTheHeckOfIt() {
throw new NumberFormatException();
}
How would you know that you need to call the above method, without checking a condition first?
Upvotes: 6
Reputation: 11182
You can assign different types of exceptions to a variable using the ternary operator and then throw the exception.
Then you can handle the case where number is smaller than 0 by catching that specific exception and re-throwing it. The other Exception should have an empty catch.
int number = 0;
RuntimeException result = number < 0 ? new NumberFormatException() : new RuntimeException();
try {
throw result;
} catch (NumberFormatException e) {
throw e;
} catch (RuntimeException e) {
// Do nothing
}
Upvotes: 0
Reputation: 27652
If I take your question literally, here is an answer. No if statement, and no switch.
public class NoIf {
static void f(int x) throws Exception {
while (x < 0) {
throw new Exception();
}
}
public static void main(String[] args) throws Exception {
System.out.println("Trying with 1...");
f(1);
System.out.println("Trying with -1...");
f(-1);
System.out.println("Done!");
}
}
Quoting Óscar López, from his more elegant answer: But why?
Upvotes: 2
Reputation: 83577
Is there a way to throw an exception in your function without using an if statement in Java?
Yes. In general, the throw
statement does not require an if
statement.
For example, if an integer is smaller than 0, I want to throw an exception
Read what you wrote here very carefully. Since you want to throw an exception only when a certain condition is true, then you must use an if statement. In general, your code should follow the words that you use to describe it.
but when checking that specific condition, I don't want to use an if(or switch) statement.
This is not possible. Checking a condition in Java requires an if
statement.
Upvotes: 0