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:
Errors in Java refer to problems that you should NOT try to catch
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!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With