1.语法:
try{
//可能出现异常的代码
}catch(异常类型1 变量名1){
//处理异常的方式1
// }catch(异常类型2 变量名2){
//处理异常的方式2
}
....
finally{
//一定会执行的代码
}
public class ExceptionTest1 {
public static void main(String[] args){
AA a=new AA();
a.test1();
}
}
class AA{
public void test1(){
String str="123";
str="abc";
try {
int num = Integer.parseInt(str);
}catch (NumberFormatException e){
System.out.println("出现数值转换异常了");
}
}
}
2.说明:
1⃣️finally可以写,也可以不写。
2⃣️使用try将肯出现异常的代码包装起来,在执行过程中,一旦出现异常,就会生成一个对应异常类的对象,根据此对象的类型,去catch中匹配。
3⃣️一旦try中的异常对象匹配到某一个catch时,就进入catch进行异常的处理,一旦处理完成,就跳出当前的try-catch结构(在没有写finally的情况下)。继续执行其后的代码。
4⃣️catch中的异常类型如果没有子父类关系,则谁声明在上,谁声明在下无所谓。
catch中的异常类型如果满足子父类关系,则要求子类一定声明在父类的上面。否则,报错。
5⃣️常用的异常对象处理的方式:
方式一:String getMessage()
方式二:printStackTrace()
6⃣️在try结构中声明的变量,在出了try结构以后,就不能再被调用
7⃣️使用try-catch-finally处理编译时异常,使得程序在编译时不再报错,但是在运行时仍可能报错,相当于我们使用try-catch-finally将一个编译时可能出现的异常,延迟到运行时出现。
8⃣️try-catch-finally结构可以嵌套。
9⃣️开发中,由于运行时异常比较常见,所以我们通常就不针对运行时异常编写try-catch-finally了。针对编译时异常,一定要考虑异常的处理。
public class ExceptionTest1 {
public static void main(String[] args){
AA a=new AA();
a.test1();
}
}
class AA{
public void test1(){
String str="123";
str="abc";
try {
int num = Integer.parseInt(str);
}catch (NumberFormatException e){
System.out.println("出现数值转换异常了");
System.out.println(e.getMessage());//处理方式一
e.printStackTrace();//处理方式二,可以查出出现异常的代码的位置
}catch (NullPointerException e){
System.out.println("出现了空指针异常");
}catch (Exception e){
System.out.println("出现异常了");
}
//在try结构中声明的变量,在出了try结构以后,就不能再被调用
// System.out.println(num);
}
}
3.finally
(1)finally是可选的
(2)finally中声明的是一定会被执行的代码。即使catch中又出现异常了,try中有return语句,catch中有return语句等情况。
(3)像数据库连接、输入输出流、网络编程Socket等资源,JVM是不能自动等回收的,因此我们需要手动的进行资源的释放。此时的资源释放,就需要声明在finally中。
public class FinallyTest {
public static void main(String[] args){
BB bb=new BB();
//bb.test1();
System.out.println(bb.method());
}
}
class BB{
public void
public int method(){
try {
int[] arr=new int[10];
System.out.println(arr[10]);
return 1;//如果没有异常就返回1
}catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
return 2;//如果有异常就返回2
}finally {
System.out.println("一定会被执行");
//如果此处也有return,则返回的是此处的return
// return 3;
}
}
public void test1(){
try{
int a=10;
int b=0;
System.out.println(a/b);
}catch (ArithmeticException e){
e.printStackTrace();
int[] arr=new int[10];
System.out.println(arr[10]);
}catch (Exception e){
e.printStackTrace();
}finally {
System.out.println("一定会被执行");
}
}
}