您好,欢迎来到图艺博知识网。
搜索
您的当前位置:首页Java高级重点知识点-17-异常

Java高级重点知识点-17-异常

来源:图艺博知识网

异常

指的是程序在执行过程中,出现的非正常的情况,最终会导致JVM的非正常停止。Java处 理异常的方式是中断处理。

异常的根类是 java.lang.Throwable,,其下有两个子类:java.lang.Error 与 java.lang.Exception。

  1. 异常分类
  • 编译时期异常:checked异常。在编译时期,就会检查,如果没有处理异常,则编译失败。(如日期格式化异常)
  • 运行时期异常:runtime异常。在运行时期,检查异常.在编译时期,运行异常不会编译器检测(不报错)。(如数学异常)

异常处理

Java异常处理的五个关键字:try、catch、finally、throw、throws

  1. 抛出异常throw

使用格式:

throw new 异常类名(参数);
public class ExceptionDemo {

    public static int getElement(int[] arr , int index){
        if (index < 0 || index >= arr.length){
            throw new ArrayIndexOutOfBoundsException("数组下标越界啦!");
        }

        int element = arr[index];
        return element;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int index = 5;
        int element = getElement(arr, index);
        System.out.println(element);
        System.out.println("over");
    }
}

  1. 声明异常throws

使用格式:

修饰符 返回值类型 方法名(参数) throws 异常类名1,异常类名2…{ }
import java.io.FileNotFoundException;
import java.io.IOException;

public class ExceptionDemo {
    public static void findFile(String file) throws FileNotFoundException,IOException{
        if (!file.equals("a.txt")){
            throw new FileNotFoundException("找不到文件");
        }

        int index = file.lastIndexOf(".");
        String prefix = file.substring(index);
        if (prefix.equals(".txt")){
            System.out.println("文件格式正确");
        }else {
            throw new IOException("文件格式不正确");
        }
    }

    public static void main(String[] args) throws IOException {
        String file = "a.txt";
        findFile(file);
        System.out.println("over");
    }
}

  1. 捕获异常try…catch

Java中对异常有针对性的语句进行捕获,可以对出现的异常进行指定方式的处理。

try{
	编写可能会出现异常的代码
}catch(异常类型 e){
	处理异常的代码
	//记录日志/打印异常信息/继续抛出异常
}
  • 该方法不处理,而是声明抛出,由该方法的调用者来处理(throws)。
  • 在方法中使用try-catch的语句块来处理异常。
import java.io.IOException;

public class ExceptionDemo {
    public static void findFile(String file) throws IOException{
        int index = file.lastIndexOf(".");
        String prefix = file.substring(index);
        if (prefix.equals(".txt")){
            System.out.println("文件格式正确");
        }else {
            throw new IOException("文件格式不正确");
        }
    }

    public static void main(String[] args){
        String file = "a.html";
        try {
            findFile(file);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        System.out.println("over");
    }
}

Throwable类中定义了一些查看方法:

  • public String getMessage() :获取异常的描述信息,原因(提示给用户的时候,就提示错误原因。
  • public String toString() :获取异常的类型和异常描述信息(不用)。
  • public void printStackTrace() :打印异常的跟踪栈信息并输出到控制台。
  1. finally 代码块

有一些特定的代码无论异常是否发生,都需要执行。因此我们就会使用finally关键字来解决这个问题

import java.io.IOException;

public class ExceptionDemo {
    public static void findFile(String file) throws IOException{
        int index = file.lastIndexOf(".");
        String prefix = file.substring(index);
        if (prefix.equals(".txt")){
            System.out.println("文件格式正确");
        }else {
            throw new IOException("文件格式不正确");
        }
    }

    public static void main(String[] args){
        String file = "a.html";
        try {
            findFile(file);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } finally {
            System.out.println("不管出不出现异常都要执行!");
        }
        System.out.println("over");
    }
}

  1. 多个异常进行捕获的方式:
  • 多个异常分别处理。
  • 多个异常一次捕获,多次处理。
  • 多个异常一次捕获一次处理。

注意:

  • 运行时异常被抛出可以不处理。即不捕获也不声明抛出。
  • 如果finally有return语句,永远返回finally中的结果,避免该情况.
  • 如果父类抛出了多个异常,子类重写父类方法时,抛出和父类相同的异常或者是父类异常的子类或者不抛出异常。
  • 父类方法没有抛出异常,子类重写父类该方法时也不可抛出异常。此时子类产生该异常,只能捕获处理,不能声明抛出

自定义异常

异常类如何定义:

  1. 自定义一个编译期异常: 自定义类 并继承于 java.lang.Exception 。
    代码示例:
	// 业务逻辑异常
public class MyException extends Exception {
	/**
	* 空参构造
	*/
	public MyException () {
	}
	/**
	*
	* @param message 表示异常提示
	*/
	public MyException (String message) {
		super(message);
	}
}
  1. 自定义一个运行时期的异常类:自定义类 并继承于 java.lang.RuntimeException 。
public class MyException extends RuntimeException {
    /**
     * 空参构造
     */
    public MyException () {
    }

    /**
     *
     * @param message 表示异常提示
     */
    public MyException (String message) {
        super(message);
    }
}

总的来说就是,继承异常类Exception或者RuntimeException,重写空参构造方法和有参构造方法。

欢迎java热爱者了解文章,作者将会持续更新中,期待各位友友的关注和收藏,另外对编程感兴趣的友友们可以加以下群共同学习。群号:1278716

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuoyibo.net 版权所有 湘ICP备2023021910号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务