Java 中的异常处理

一.Java中异常的体系结构:如图E001.jpe

  Error:严重问题,不需要程序来处理,(内存不足,硬盘问题)
  Exception:异常类,表示程序本身可以处理的问题(程序设计出问题)
  RuntimeException:在编译期不检查,出现问题后,要修改程序,编译没有问题,执行的时候出问题
  非 RuntimeException: 在编译期就必须处理,不处理不能正常编译,比如:数组索引越界。
二.Throwable 类 中三个重要的异常处理方法
   e.toString();最简单告诉是那里报错,如下B1
   e.getMessage();较详细,可以给出类名和报错的地方:如下B2
   e.printStackTrace();最详细,给出涉及到那里调用,类名和报错的地方,如下B3
   eg :
   *************B3*************
   java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
       at EcepetionClass.TestDemo.Meoth(TestDemo.java:13)
       at EcepetionClass.TestDemo.main(TestDemo.java:6)
   **************B1************
   Index 3 out of bounds for length 3
   **************B2*************
   java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
三.throws 抛出异常,但不处理异常,那里调用,那里在用try...catch{} 如:代码中:A3
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class TestDemo {
    public static void main(String[] args) {
        System.out.println("开始");
        Meoth(); // A1,
        System.out.println("结束"); //A2
        System.out.println("------------");
        try { //调用了A3处,所以,这里处理异常,程序才能向下执行。
            Meoth2();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private static void Meoth() {
        try { // 经过异常处理后,程序可以向下执行,A1抛出异常后,可以继续执行:A2
            int[] arrA = {1, 2, 3};
            System.out.println(arrA[3]);
        } catch (ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
            System.out.println("**************************");
            System.out.println(e.getMessage());
            System.out.println("***************************");
            System.out.println(e.toString());
        }
    }
    public static void Meoth2() throws ParseException { //A3 这是只是抛出异常,并不处理,谁调用谁处理
        String dateEg ="2020-02-28";
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
        sdf.parse(dateEg);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值