异常分类: 可查异常,运行时异常和错误3种


异常分类: 可查异常,运行时异常和错误3种
其中,运行时异常和错误又叫非可查异常

一、可查异常(CheckedException)

可查异常: CheckedException
可查异常即必须进行处理的异常,要么try catch住,要么往外抛,谁调用,谁处理,比如 FileNotFoundException
如果不处理,编译器,就不让你通过

比如要打开d盘的LOL.exe文件,这个文件是有可能不存在的
Java中通过 new FileInputStream(f) 试图打开某文件,就有可能抛出文件不存在异常FileNotFoundException
如果不处理该异常,就会有编译错误
package exception;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 *
 *
 * @author
 * @version 1.0
 * @date 2021/1/4 13:22
 */
public class TestCheckedException {

  public static void main(String[] args) {
    File file = new File("d:/LOL.exe");
    //试图打开文件LOL.exe,会抛出FileNotFoundException,如果不处理该异常,就会有编译错误
    try {
      System.out.println("试图打开文件 d:/LOL.exe");
      new FileInputStream(file);
      System.out.println("成功打开");
    } catch (FileNotFoundException e) {
      System.out.println("d:/LOL.exe 不存在");
      e.printStackTrace();
    }
  }

}

二、运行时异常(RuntimeException)

运行时异常RuntimeException指: 不是必须进行try catch的异常
常见运行时异常:
除数不能为0异常:ArithmeticException
下标越界异常:ArrayIndexOutOfBoundsException
空指针异常:NullPointerException
在编写代码的时候,依然可以使用try catch throws进行处理,与可查异常不同之处在于,即便不进行try catch,也不会有编译错误
Java之所以会设计运行时异常的原因之一,是因为下标越界,空指针这些运行时异常太过于普遍,如果都需要进行捕捉,代码的可读性就会变得很糟糕。
package exception;

/**
 *
 * @author
 * @version 1.0
 * @date 2021/1/4 14:16
 */
public class TestRuntimeException {

  public static void main(String[] args) {
    //任何除数不能为0:ArithmeticException
    int i = 10/0;
    //下标越界异常:ArrayIndexOutOfBoundsException
    int[] array = new int[5];
    array[10] = 10;
    //空指针异常:NullPointerException
    String str = null;
    str.length();
  }

}

三、错误(Error)

错误Error,指的是系统级别的异常,通常是内存用光了
在默认设置下,一般java程序启动的时候,最大可以使用16m的内存
如例不停的给StringBuffer追加字符,很快就把内存使用光了。抛出OutOfMemoryError
与运行时异常一样,错误也是不要求强制捕捉的
package com.tinet.exception;

/**
 *
 * @author chenheng@ti-net.com.cn
 * @version 1.0
 * @date 2021/1/4 14:22
 */
public class TestError {

  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < Integer.MAX_VALUE; i++) {
      sb.append(i);
    }
  }

}

四、三种分类

总体上异常分三类:
1. 错误
2. 运行时异常
3. 可查异常

在这里插入图片描述

五、参考链接

1、异常分类

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值