Java中常见异常
1.Exception类,也就是常说的受检异常或者Checked Exception,即编译时异常。
2.RuntimeException类,既运行时异常。
Javac编译器会强制检查编译时异常必须抛出或处理。运行时异常往往是代码不规范导致运行的时候所抛出异常,需要开发人员自己发现和处理。在大部分情况下的异常,我们都是直接忽略一路往外抛。所以渐渐的Java程序员处理Exception的常见手段就是try catch捕获后抛出RuntimeException或者自定义的通用异常。
try {
} catch(Exception e) {
throw new RuntimeException(e);
}
@SneakyThrows的作用
编写代码出现异常时,如果我们不想(或不能)在抛出异常的地方直接处理时可以使用该注解。如下段代码SimpleDateFormat.parse()方法会抛出异常 throws ParseException
public static void main(String[] args) {
System.out.println(getModifyMoth("2022-01-12", 1, "yyyy-MM-dd"));
}
@SneakyThrows()
public static String getModifyMoth(String str, Integer moth, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = sdf.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, moth);
return sdf.format(calendar.getTime());
}
编译Java文件后反编译class查看一下效果
public static void main(String[] args) {
System.out.println(getModifyMoth("2022-01-12", Integer.valueOf(1), "yyyy-MM-dd"));
}
public static String getModifyMoth(String str, Integer moth, String format) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = sdf.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(2, moth.intValue());
return sdf.format(calendar.getTime());
} catch (Throwable $ex) {
throw $ex;
}
}
通过查看@SneakyThrows,可以看出该注解还支持自己设置需要忽略的异常
@Target(作用域):ElementType.METHOD 方法,ElementType.CONSTRUCTOR 构造方法
@Retention(生命周期):RetentionPolicy.SOURCE 源文件(即Java编译为class文件后注解就没了)
value(类似普通类中定义的属性):通过泛型指定元素必须是继承Throwable类的数组
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.SOURCE)
public @interface SneakyThrows {
Class<? extends Throwable>[] value() default {Throwable.class};
}
自定义忽略异常
@SneakyThrows(value = {ParseException.class})
public static String getModifyMoth(String str, Integer moth, String format) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = sdf.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, moth);
return sdf.format(calendar.getTime());
}