java异常以及异常处理

异常

异常(exception):是在运行过程中代码序列中产生一种例外情况。

异常的类型有
在这里插入图片描述

1、try-catch结构

使用 try 和 catch 关键字可以捕获异常。try/catch 代码块放在异常可能发生的地方。

try/catch代码块中的代码称为保护代码,使用 try/catch 的语法如下:

try
{
    
    
   // 程序代码
}catch(ExceptionName e1)
{
    
    
   //Catch 块
}

例如

public static void main(String[] args) {
    
    
        try{
    
    
            int num = 5/0;
            System.out.println(num);
        }catch (ArithmeticException e){
    
    
            System.out.println("除数不能为零");
        }finally {
    
    
            System.out.println("回收代码资源");
        }
        try{
    
    
            String string = null;
            System.out.println(string.length());
        }catch (NullPointerException e){
    
    
            System.out.println("数值不能为空");
        }finally {
    
    
            System.out.println("回收代码资源");
        }
        System.out.println("程序继续执行");
    }

2、多重try-catch结构

一个 try 代码块后面跟随多个 catch 代码块的情况就叫多重捕获。

try{
    
    
   // 程序代码
}catch(异常类型1 异常的变量名1){
    
    
  // 程序代码
}catch(异常类型2 异常的变量名2){
    
    
  // 程序代码
}catch(异常类型3 异常的变量名3){
    
    
  // 程序代码
}

例如

try {
    
    
    file = new FileInputStream(fileName);
    x = (byte) file.read();
} catch(FileNotFoundException f) {
    
     // Not valid!
    f.printStackTrace();
    return -1;
} catch(IOException i) {
    
    
    i.printStackTrace();
    return -1;
}

3、throws/throw 关键字

如果一个方法没有捕获到一个检查性异常,那么该方法必须使用 throws 关键字来声明。throws 关键字放在方法签名的尾部。

也可以使用 throw 关键字抛出一个异常,无论它是新实例化的还是刚捕获到的。

例如

import java.io.*;
public class className
{
    
    
  public void deposit(double amount) throws RemoteException
  {
    
    
    // Method implementation
    throw new RemoteException();
  }
  //Remainder of class definition
}
import java.io.*;
public class className
{
    
    
   public void withdraw(double amount) throws RemoteException,
                              InsufficientFundsException
   {
    
    
       // Method implementation
   }
   //Remainder of class definition
}

4、finally关键字

finally 关键字用来创建在 try 代码块后面执行的代码块。

无论是否发生异常,finally 代码块中的代码总会被执行。

在 finally 代码块中,可以运行清理类型等收尾善后性质的语句。

public class ExcepTest{
    
    
  public static void main(String args[]){
    
    
    int a[] = new int[2];
    try{
    
    
       System.out.println("Access element three :" + a[3]);
    }catch(ArrayIndexOutOfBoundsException e){
    
    
       System.out.println("Exception thrown  :" + e);
    }
    finally{
    
    
       a[0] = 6;
       System.out.println("First element value: " +a[0]);
       System.out.println("The finally statement is executed");
    }
  }
}

finally 可以把它看成为回收资源。

5、总结

  1. 运行时发生的错误称为异常;
  2. Java使用try,catch,throw,throws和finally来处理Java异常;
  3. 被监控的代码写在try块中,用来捕获和处理异常的代码写在catch块中,finally中放置必须要执行的代码;
  4. 要手动引发异常,可以使用关键字throw。抛到方法外部的任何异常都必须用throws子句指定。

猜你喜欢

转载自blog.csdn.net/s001125/article/details/110489235