javaexceptioncustom-errors

How can I raise an error in if-else function in java


All the googling I've done seems focused on "catching" errors. I want to be able to raise my own if certain conditions are met. I tried using the Error() class and its subclasses but Eclipse doesn't recognize them.

This is what I want to do:

if(some_condition) {
    foobar();
}
else {
    // raise an error
}

Stupid question, I know, but I've done my googling and I figure someone out there would be able to help me.

Thanks in advance!


Thanks everyone! If you are reading this in the future, here's the skinny:

  1. Errors in Java refer to problems that you should NOT try to catch

  2. Exceptions refer to errors that you may want to catch.

Here's my "fixed" code:

if(some_condition) {
    foobar();
}
else {
    throw new RuntimeError("Bad.");
}

I used RuntimeError() because, as one answer pointed out, I don't have to declare that I'm throwing an error beforehand, and since I'm relying on a condition, that's very useful.

Thanks all!


Solution

  • Here you go:

    throw new java.lang.Error("this is very bad");
    

    More idiomatic to throw a subclass of Exception. RuntimeException in particular is unchecked (e.g., methods don't need to declare that they might throw it). (Well, so is Error, but it's supposed to be reserved for unrecoverable things).

    throw new java.lang.RuntimeException("this is not quite as bad");
    

    Note: you don't actually have to construct them right at that moment. You can throw pre-constructed ones. But one thing nice about constructing them is they record the line of code they were on and the complete call-stack that happened at the time of construction, and so constructing a new one right when you throw it does inject it with very helpful diagnostic information.