异常的处理分为消极的处理(自己处理不了,就往调用它的地方上抛throws,异常没有解决,只是抛出)和积极处理(异常捕获,捕捉异常通过try-catch语句或者try-catch-finally语句实现)。
(推荐教程:java入门教程)
消极的处理:
语法:
public void m1() throws 异常类名1,异常类名2{}
允许编译通过。
当上抛的异常为非运行(已检查)时异常时,调用此方法的调用者必须处理。
当上抛的异常为运行(未检查)时异常时,可以处理可以不处理。
积极的处理:(异常捕获)
将异常直接捕获,并且做出处理。
语法:
try{ //异常代码}catch(异常类名 引用名){ //当异常产生执行的代码}
try 后的catch代码块只能匹配成功一个。
catch后声明的异常为父类时,它能够捕捉的异常为它本身+所有子类异常(多态的体现)。
注意:catch代码块捕获异常时,子类异常必须定义在父类异常前面,否则会编译出错。
(视频教程推荐:java视频教程)
finally代码块:一定会执行此代码块中的代码,常用来关闭资源。
try{}catch(){}finally{//无论是否产生异常,一定会去执行的代码}
注意:finally代码块中不要定义return语句。
举例:
package work;import java.io.EOFException;import java.io.FileNotFoundException;import java.io.IOException;import java.sql.SQLException;import java.util.Scanner;/** * @author 超伟 * @date 2019年5月13日 * @version 1.0.0 */public class t4 {public static void main(String[] args) {System.out.println("main1");int n;Scanner sc = new Scanner(System.in);n = sc.nextInt();ma(n);System.out.println("main2");}public static void ma(int n){try {System.out.println("m1");mb(n);System.out.println("m2");} catch (EOFException e) {//e.printStackTrace();System.out.println("EOFException ");} catch (IOException e) {System.out.println("IOException e111");}catch (SQLException e) {System.out.println("SQLException");}catch (Exception e) {System.out.println("Exception");}finally{System.out.println("in finally");}}public static void mb(int n) throws Exception {System.out.println("mb1");if (n==1) {throw new EOFException();}if (n==2) {throw new FileNotFoundException();}if (n==3) {throw new SQLException();}if (n==4) {throw new NullPointerException();}System.out.println("mb2");}}程序运行结果为:main11m1mb1EOFException in finallymain2
以上就是java中的异常如何处理的知识。速戳>>知识兔学习精品课!