Java中的异常类型及区别?

戚薇 Java面经 发布时间:2023-06-30 11:00:11 阅读数:18434 1
下文笔者讲述java中常见的异常类型简介及区别,如下所示

Java中异常类型

 
检查型异常(checked exception)
  检查异常也称为“编译时异常”
    Java认为Checked异常都是可以被处理的异常
	所以Java程序必须显式处理 Checked 异常
	如果程序没有处理 Checked 异常
	该程序在编译时就会发生错误无法编译

非检查型异常(unchecked exception)
    非检查型异常又称运行时异常
	运行时异常都是RuntimeException类及其子类异常
	如
	  NullPointerException、IndexOutOfBoundsException 等
	  这些异常是不检查异常
	  程序中可以选择捕获处理
	  也可以不处理
	  这些异常一般由程序逻辑错误引起
	  程序应该从逻辑角度尽可能避免这类异常的发生。

检查类异常的处理方式

方式1:
   直接向上抛出

方式2:
   使用try catch捕捉

直接向上抛出

  
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
 
public class TestClass {
    public static void main(String[] args) {
        try {
            TestClass testClass = new TestClass();
            String str = testClass.getFile("D:/test.txt");
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    private String getFile(String filePath) throws IOException {
        File file = new File(filePath);
        return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
    }
}

使用 try-catch 语句进行处理

import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
 
public class TestClass {
    public static void main(String[] args) {
        Demo testClass = new TestClass();
        TestClass str = testClass.getFile("D:/test.txt");
        System.out.println(str);
    }
 
    private String getFile(String filePath) {
        try {
            File file = new File(filePath);
            return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
 
}

检查型异常和非检查型异常的区别

 1.非检查异常不需要在方法或者是构造函数上声明
     方法或构造函数的运行可能会抛出这样的异常

 2.非检查异常可以传播到方法或构造函数的外面

 3.检查型异常必须要用 throws 语句在方法或者是构造函数上进行声明
    或使用 try-catch 语句进行捕获并处理
     否则程序无法正常编译。

Java常见的异常类型

NullPointerException
   空指针异常
    操作一个null对象的方法或属性时触发

OutOfMemoryError
   内存异常异常,这不是程序能控制的
    指要分配的对象的内存超出了当前最大的内存堆
	需要调整堆内存大小(-Xmx)以及优化才程序

IOException
   IO
    即:input,output,我们在读写磁盘文件
	 网络内容的时候会发生的一种异常
	 这种异常是受检查的异常,需要手工捕获

FileNotFoundException
   文件找不到异常
   当文件不存在就会抛出这种异常

ClassNotFoundException
   类找不到异常
   在类路径下不能加载指定的类

ClassCastException
   类型转换异常
   如将一个数字强制转换成字符串
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaMianJing/202306/16880940496940.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者