使用assert的好处就是比较简介,不用加try catch就可以附加一些预期的提示信息,方便定位问题
import org.springframework.util.Assert; public class Demo { public static void main(String[] args) { String location = null; Assert.notNull(location, "Location must not be null"); System.out.println("location = [" + location + "]"); } }
Output:
Exception in thread "main" java.lang.IllegalArgumentException: Location must not be null at org.springframework.util.Assert.notNull(Assert.java:115) at Demo.main(Demo.java:9) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)