一、什么是java异常
异常是一种用于处理程序错误和异常情况的机制,分为两类:
- 受检异常:在方法签名中显示声明,声明方式为throws关键字加上抛出的异常类型,或者使用try-catch。
- 非受检异常。不需要显示声明,直接抛出即可。包括运行时异常和错误。
在 Java 中,运行时异常(RuntimeException)和它的子类属于非受检异常(Unchecked Exception),不需要在方法签名中显式声明,并且也不强制要求在方法调用时进行异常处理。
虽然运行时异常不需要强制要求进行异常处理,但是我们仍然推荐使用 try-catch 块来捕获和处理运行时异常。这是因为如果不对运行时异常进行处理,异常会继续向上层方法传递,直到程序终止,给调试和排查错误带来一定困难。
受检异常:
Exception类的层次
二、如何处理Java异常
受检异常处理如下:
package com.demo.exception;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* @Description
* @Author 大雄 <1194353393@qq.com>
* @Version V1.0.0
* @Since 1.0
* @Date 2023/7/24 8:25
*/
public class CheckedException {
public void throwableMethod() throws IOException {
String filePath = "C:\\Users\\大雄\\Desktop\\demo.png";
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
String line = bufferedReader.readLine();
while (line != null) {
System.out.println(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
}
public void trycatchMehtod() {
String filePath = "C:\\Users\\大雄\\Desktop\\demo.png";
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filePath));
String line = bufferedReader.readLine();
while (line != null) {
System.out.println(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
// 受检异常有两种处理方式,一种是通过throwable抛出异常。一种是try-catch
new CheckedException().throwableMethod();
// new CheckedException().trycatchMehtod();
}
}
非受检异常处理如下:
package com.demo.exception;
import java.util.ArrayList;
/**
* @Description
* @Author 大雄 <1194353393@qq.com>
* @Version V1.0.0
* @Since 1.0
* @Date 2023/7/24 8:26
*/
public class UncheckedException {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
String result = "";
try {
result = arrayList.get(3);
} catch (Exception e) {
System.out.println(e.toString());
}
System.out.println(result);
}
}
三、自定义异常
在Java中,我们可以自定义异常类来处理程序中出现的异常情况。自定义异常通常对于特定异常情况进行更加准确和详细的处理,同时也可以方便地提供异常信息和调试信息,以便程序调试和排除错误。
在Java中自定义异常,注意一下几点:
- 所有异常都必须是Throwable的子类
- 如果希望写一个受检异常,则需要继承Exception类。自定义异常默认都是受检异常。
- 如果希望写一个非受检异常,则需要继承RuntimeException类。
package com.demo.exception;
/**
* @Description
* @Author 大雄 <1194353393@qq.com>
* @Version V1.0.0
* @Since 1.0
* @Date 2023/7/24 8:56
*/
public class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
public static void main(String[] args) throws InvalidAgeException {
int age = 130;
if (age < 0 || age > 120) {
throw new InvalidAgeException("age should be between 0 and 120");
}
}
}