Java学习: 异常捕获

1.异常类型

        异常Exception分为两类,一类为Check Exception,一类为Uncheck Exception其中Exception的子类除RuntimeException外都为Check Exception,而RuntimeException及其子类都为Uncheck Exception异常。

  • 数组越界:ArrayIndexOutOfBoundsException
  • 字符转换数字异常:NumberFormatException
  • 类型转换异常:ClassCastException
  • 文件未找到异常:FileNotFoundException
  • 创建对象异常:InstantiationException
  • 断言错误异常:AssertionError
  • 虚拟机异常:VirtualMachineError
  • 线程终止异常:ThreadDeath

2.try-catch语句

  • try:在运行的代码里,尝试捕获错误。
  • catch:捕获错误后,进行的措施。
  • 两者要搭配使用
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    while (sc.hasNext()) {
        String choice = sc.next();
        try {
            if (choice.equals("number"))
                throw new NumberFormatException();
            else if (choice.equals("illegal")) {
                throw new IllegalArgumentException();
            } else if (choice.equals("except")) {
                throw new Exception();
            } else
            break;
        }//分别捕获
        catch(NumberFormatException e){
            System.out.println("number format exception");
            System.out.println(e);
        }catch( IllegalArgumentException e){
            System.out.println("illegal argument exception");
            System.out.println(e);
        }catch(Exception e){
            System.out.println("other exception");
            System.out.println(e);
        }//多重捕获,注意括号里的异常不能有继承关系。
        catch(IOException| ClassNotFoundException | ClassCastException e){
            System.out.println(e);
        }
    }
    sc.close();
}

3.异常继承结构图

  • 在多重捕获捕捉异常继承时候要注意,不能有继承关系。有捕获的异常必须处理。
  • 捕获异常父类,则可以捕获任何子类异常。
  • 异常也为类,可以用instanceof判断类型,即用if语句配合多重捕获,简化代码。

    Exception的子类: 受检异常,必须try/catch。

IOException、
ReflectiveException、

    RuntimeException子类:非受检异常,运行时候发生的异常,不必try/catch。

NumberFormatException、ArrayIndexOutOfBoundsException
ClassCastException、ClassCastException

    Error子类:程序一般不可能发生的异常。属于严重错误。

VirtualMachineError、
AssertionError、

4. 使用finally

  • 要和try搭配使用。
  • 无论try是否发生异常都会执行finally区块代码。

import java.util.Scanner;

public class Main{
    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String choice = sc.next();
            try{
                //执行代码
            }
            finally{
                //执行代码
            }
            sc.close();
        }
    }
}

5.throw和throws用法

  • throw用在方法内部,表示抛出异常。
  • throws用在方法头部,表示可能抛出那些异常。

举个例子:

public void setName(String name) throws IllegalNameException {
        if (name.charAt(0) >= '0' && name.charAt(0) <= '9'){
            throw new IllegalNameException(name);
        }
        this.name = name;
}

        这个代码throws说明可能会抛出自定义异常 IllegalNameException,然后if条件判断名字的首字母是否是数字,如果是则抛出异常,异常也是类,需要new来创建对象。

6.自定义异常

        自定义异常需要继承父类异常,所有的异常都继承Throwable。打印异常对象时候,会自动调用toString方法来输出异常。无论是无参构造方法,还是有参构造方法,都调用父类无参构造器。

class IllegalScoreException extends RuntimeException {
    String message;
    public IllegalScoreException() {
    }

    public IllegalScoreException(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return "IllegalScoreException: score out of range, score=" + message;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值