在开发中,为了适应业务的开发需求, 在 Java 中可以根据业务的异常情况自定义异常。
所有的自定义异常都必须是 Throwable 的子类,在自定义继承时可以继承于 Exception 或者它的子类。
RuntimeException
Objects由一些静态的实用方法组成,这些方法是null-save(空指针安全的)或 null-tolerant(容忍空指针的),那么在它的源码中,对对象为null的值进行了抛出异常操作。Objects通过调用requireNonNull(T obj)方法查看调用对象是否为null。
public static <T> T requireNonNull(T obj) {
if (obj == null) throw new NullPointerException(); return obj; }
从上面源码可以看出,如果传递对象为 null,requireNonNull 方法会抛出 NullPointerException 异常,否则返回该对象。
public class MyException extends Exception { public MyException() { } // 无参构造 public MyException(String msg) { super(msg); // msg : 异常提示信息 } public MyException(Throwable throwable) { super(throwable);// throwable 类型 } }
public class MyRuntimeException extends RuntimeException { public MyRuntimeException() { } // 无参构造 public MyRuntimeException(String msg) { super(msg); // msg : 异常提示信息 } public MyRuntimeException(Throwable throwable) { super(throwable);// throwable 类型 } }
public class ExceptionDemo { public static void main(String[] args) throws Exception { int i = demo(3); System.out.println("i = " + i); } public static int demo(int index) throws MyException{ int[] arr = {1,2,3}; if(index >= arr.length || index < 0) throw new MyRuntimeException("您传递的索引错误,数组索引在0-2之间"); return arr[index]; } }
public static void main(String[] args) throws Exception { Integer i = 10; Integer i2 = Objects.requireNonNull(i); System.out.println(i2); }
原文:https://www.cnblogs.com/lingq/p/12943295.html