线程终止
异常抛出主要有error和exception两种,error程序直接终止,线程当然就是终止了;exception分为两种运行时和编译时,运行时异常常被捕获或抛出,程序会继续运行,没有被捕获线程就停止了;而编译时异常直接就无法完成编译了。
编译时异常 | 运行时异常 |
---|---|
SQLException | NullPointerException |
IOException | ClassCastException(对象强制类型转换出错) |
ClassNotFoundException | ArrayIndexOutOfBoundsException(数组下标越界) |
ArithmeticException(算数错误情形) |
异常处理
1、标准错误输出流
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
System.out.println("请输入被除数:");
try {
int num1=input.nextInt();
System.out.println("请输入除数:");
int num2=input.nextInt();
System.out.println(String.format("%d / %d = %d",
num1, num2, num1 / num2));
}catch (Exception e) {
System.err.println("出现错误:被除数和除数必须是整数,"+
"除数不能为零。");
System.out.println(e.getMessage());
}
}
System.err.println():标准错误输出流,这种输出方式可以输出错误的消息,在控制台呈现红色。
2、try-catch、try-catch-finally、多重catch块
try-catch-finally 程序块的流程大致分为两种情况:
- 如果try块中所有语句正常执行完毕,那么finally块就会被执行。
- 如果try语句在执行过程中碰到异常,无论这种异常能否被catch块捕获到,都将执行finally块中的代码。
- 在写异常处理的时候,一定要把异常范围小的放在前面,范围大的放在后面
try-catch-finally结构中try块是必须有的,catch和finally块为可选,但两者至少必须出现其中之一
3、try-catch-finally中包含return的情况
public class Main {
public static void main(String args[]) {
// 顺序执行即可
try {
} catch () {
} finally {
}
return;
// 执行try块中(异常时执行catch())的return之前的代码,然后执行finally块,
// 最后执行try块(或者catch)中的return。
// 此时程序已经返回,不再执行finally{}后面的return了。
try {
return;
} catch () {
return;
} finally {
}
return;
// 执行try或者catch中的return语句之前,都会先执行finally语句,
// 如果finally中有return语句,那么程序就直接return了。
try {
return;
} catch () {
return;
} finally {
return;
}
return;
}
}
总结:如果finally存在的话,任何执行try 或者catch中的return语句之前,都会先执行finally语句, 如果finally中有return语句,那么程序就return了。所以finally中的return是一定会被return的,编译器把finally中的return实现为一个warning。
4、throws 和 throw
throws 声明异常,throws是用来声明一个方法可能抛出的所有异常信息,throws是将异常声明但是不处理,而是将异常往上传,谁调用我就交给谁处理。
throw 抛出异常,throw抛出的一个具体的异常类型。
public class Test {
// throws 声明异常
public static void Test3() throws NumberFormatException{
String s = "abc";
System.out.println(Double.parseDouble(s));
}
public static void main(String[] args) {
try {
Test3();
} catch (NumberFormatException e) {
// 捕获异常
System.err.println("非数据类型不能转换。");
}
}
}
public class Test2 {
public static void main(String[] args) {
String s = "abc";
if(s.equals("abc")) {
// throw 抛出异常,throw(异常对象)
throw new NumberFormatException();
} else {
System.out.println(s);
}
}
}