Take the 2-minute tour ×

I am having trouble understanding how a RuntimeException works. I have searched through Google.

The application I want to use one in is a cash register program that just simulates two cash registers working. I will use two classes: one with the input and output and the other with all my methods and such.

In my assignment description, it said to make sure that your methods catch any violated preconditions ny throwing a RuntimeException with an informative error.

I am not sure how to implement this - I am not looking for syntax here but just how to set something like this up, seeing as I don't have a full understanding of how the RuntimeException works or what preconditions for a method even are. How could I implement one?

share|improve this question

2 Answers 2

up vote 5 down vote accepted

A precondition is something that your method documents must be true before the method will execute properly. For example, you could have a precondition that an argument must be positive. (Another example is that the object must be in a certain state.)

RuntimeException is a subclass of Exception which is special in that exceptions of type RuntimeException (and its subclasses) are unchecked - you don't need to declare that you throw them as part of the method signature. One example of a RuntimeException is IllegalArgumentException.

So if we have a method which will only work if it's called with a positive number, you might have:

public void foo(int x) {
    if (x <= 0) {
        throw new IllegalArgumentException("x must be positive");
    // Rest of the code here

This protects the rest of the method from trying to operate in a situation it was never intended for.

share|improve this answer
I understand, this helps a lot thank you. But what I don't get is what you mean when you say "RuntimeException is a subclass of Exception" or " unchecked - you don't need to declare that you throw them as part of the method signature" sorry I get lost in jargon –  binary_Kramer Feb 20 '13 at 23:17

I think you need to increase your know-how level with reading some articles before the implementation which is more further step. Firstly you can research about Throwable class which is the superclass of all errors and exceptions in Java. You can check this question also for it.

Then Exceptions need to be visited. Oracle tutorials tells more about run-time handling. Or you can check this article also which illustrates the title into a real-life example.

Also about Error and Exception hierarchy this graphic makes it easier to understand:

Throwable Family

share|improve this answer

Your Answer


