0

Let's say we have following code:

public void a(String a) {
   if (a == null) {
      throw new IllegalArgumentException();
   }
}

public void b(Queue<Integer> b) {
   if (b == null) {
      throw new IllegalArgumentException();
   }
}

public void c(Stack<Integer> c) {
   if (c == null) {
      throw new IllegalArgumentException();
   }
}

Is it possible to write a method that do the throw new exception job ? That is something like this:

public void a(String a) {
   check(a);
}

public void b(Queue<Integer> b) {
   check(b);
}

public void c(Stack<Integer> c) {
   check(c);
}

Notice that their types of parameter is not the same.

1
  • 1
    void check(Object o) { if (o == null) { throw new IllegalArgumentException(); } } ? Commented Apr 10, 2016 at 20:42

2 Answers 2

1

you can be more generic like:

public void check(Object a) {
   if (a == null) {
      throw new IllegalArgumentException();
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is perfectly adequate; but note how Guava's Preconditions.checkNotNull is implemented with generics, to allow you to write something like this.a = check(a);.
0
public static <X extends Throwable, T> T ifNullThrow(final T value, @NonNull final Supplier<? extends X> exceptionSupplier)
        throws X {
    if (value != null) {
        return value;
    }
    throw exceptionSupplier.get();
}

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.