异常
throw 和 throws
throw 是主动抛出异常,手动创建一个异常对象,抛出
异常是 Java 自主机制,Java 自动执行异常的流程
1、检测所有的代码,类加载的阶段仅仅进行语法错误的检查,编译,再运行,在运行阶段进行检测
2、发现运行时错误,则根据错误类型创建一个对应的异常对象,并抛出
3、对异常对象进行处理,手动 try-catch 代码进行捕获,交给 Java 虚拟机进行处理
package test;
public class Test {
public static void main(String[] args) throws Exception {
String str = "Jav";
test(str);
}
public static void test(String string){
try{
if(!string.equals("Java")){
//主动创建异常对象
RuntimeException runtimeException = new RuntimeException("单词拼写错误");
//抛出异常
throw runtimeException;
} else {
System.out.println("ok");
}
}catch (Exception e){
System.out.println("异常类型:"+e.getClass()+",异常信息:"+e.getMessage());
}
}
}
Java 默认异常机制只能满足最基础的操作,真正的企业级项目中是远远不够的,需要手动结合具体业务场景进行异常的创建及抛出。
throws 标识方法可能会出现某些异常,修饰方法的
并不是每个方法都需要进行修饰,风险较大(抛出异常的概率)的方法需要进行标识,风险小的不需要进行标识。
给方法添加标识的目的是告诉开发者该方法需谨慎调用,该 try-catch 就需要 try-catch
package test;
public class Test {
public static void main(String[] args) {
test3();
}
public static void test(String string){
try{
if(string.equals("a")){
throw new ArithmeticException();
}
if(string.equals("b")){
throw new NullPointerException();
}
if(string.equals("c")){
throw new ArrayIndexOutOfBoundsException();
}
} catch (RuntimeException e){
System.out.println("【异常】类型:" + e.getClass() + "信息:" + e.getMessage());
}
}
public static void test4() throws Exception{
test3();
}
public static void test3() {
try {
test2("1");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void test2(String string) throws Exception {
int i = Integer.parseInt(string);
System.out.println(i);
}
}
自定义异常
Java 提供的异常类无法满足一些特定业务需求的时候,开发者自己进行扩展即可,继承
方法中抛出的异常类(本身或者其父类)是 Exception 的时候,必须给方法添加 throws 修饰
如果方法中抛出的异常类(本身或其父类)是 RuntimeException,则不需要进行 throws 的修饰
package test;
public class MyNumberException extends Exception {
public MyNumberException(String message){
super(message);
}
}
public static void add(Object object) throws Exception {
//如何判断object是否为Integer类型?
if(!(object instanceof Integer)){
throw new MyNumberException("【传入的参数不是整数类型】");
} else {
int num = (int) object;
num++;
System.out.println(num);
}
}