Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom exception with Guava Preconditions

It's very simple question, I often use com.google.common.base.Preconditions in my projects to validate arguments and parameters, for example:

Preconditions.checkNotNull(parameter, "message");
Preconditions.checkArgument(parameter > 0, "message");

this code may produce IllegalArgumentException or NPE. But very often I need throw own exception. How can I do it by this library? Or maybe you can advise another one? thank you in advance!

UPDATE: I understand, that I can to create own simple utility class, but I'm interested to find ready-made solutions. Please, let me know, if somebody know it's possible.

like image 786
maxi Avatar asked Dec 20 '13 15:12

maxi


2 Answers

If you want to throw your own exception, just create your own class with similar methods to the ones in Preconditions. Each of those methods is extremely simple - adding some sort of "plug-in" ability to allow the exception class to be specified would really be overkill compared with writing your own.

You could always use the source of Preconditions as a starting point.

like image 142
Jon Skeet Avatar answered Sep 28 '22 05:09

Jon Skeet


That's the solution I finally came to. It does exactly what I wanted. Might be useful to anybody:

import java.lang.reflect.InvocationTargetException;

// IMPORTANT: parameter exClass must have at least no args constructor and constructor with String param
public class Precondition {

public static <T extends Exception> void checkArgument(boolean expression, Class<T> exClass) throws T {
    checkArgument(expression, exClass, null);
}

public static <T extends Exception> void checkArgument(boolean expression, Class<T> exClass, String errorMessage, Object... args) throws T {
    if (!expression) {
        generateException(exClass, errorMessage, args);
    }
}

public static <T extends Exception> void checkNotNull(Object reference, Class<T> exClass) throws T {
    checkNotNull(reference, exClass, null);
}

public static <T extends Exception> void checkNotNull(Object reference, Class<T> exClass, String errorMessage, Object... args) throws T {
    if (reference == null) {
        generateException(exClass, errorMessage, args);
    }
}

private static <T extends Exception> void generateException(Class<T> exClass, String errorMessage, Object... args) throws T {
    try {
        if (errorMessage == null) {
            throw exClass.newInstance();
        } else {
            throw exClass.getDeclaredConstructor(String.class, Object[].class).newInstance(errorMessage, args);
        }
    } catch (InstantiationException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        e.printStackTrace();
    }
}

}

like image 32
maxi Avatar answered Sep 28 '22 05:09

maxi