Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 283
Eli Dinkelspiel Avatar asked Jan 22 '16 03:01

Eli Dinkelspiel


People also ask

How do you raise errors in Java?

You can throw an exception in Java by using the throw keyword. This action will cause an exception to be raised and will require the calling method to catch the exception or throw the exception to the next level in the call stack.

How do you throw an exception in if else condition in Java?

Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.

How do you throw an exception in if else?

We can define our own set of conditions or rules and throw an exception explicitly using throw keyword. For example, we can throw ArithmeticException when we divide number by 5, or any other numbers, what we need to do is just set the condition and throw any exception using throw keyword.


1 Answers

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.

like image 150
G. Sylvie Davies Avatar answered Oct 07 '22 00:10

G. Sylvie Davies