异常
概述
异常概述:程序出现了不正常的情况。
异常体系:
Error:严重问题,不需要处理
Exception:称为异常类,它表示程序本身可以处理的问题
- RuntimeException:在编译期不需要检查的,出现问题后,我们需要回来修改代码。
- 非RuntimeException:编译期就必须处理的,否则程序不能通过编译,就更不能正常运行了。
JVM默认处理方案
如果程序出现了问题,我们没有做任何处理,最终JVM会做默认的处理。
- 把异常的名称,异常的原因以及异常出现的位置输出在控制台
- 程序停止执行
入门案例
public class Main {
public static void main(String[] args) {
System.out.println("开始");
fc();
System.out.println("开始");
}
public static void fc(){
int arr [] = {1, 2, 3, 4};
System.out.println(arr[4]); // 常见的错误之 数组下标访问越界
}
}
运行结果:
异常处理
如果程序出现问题,我们需要自己来处理,有两种方案:
- try…catch
- throws
try catch
- 格式
try{
可能出现异常的代码;
} catch(异常类名 变量名){
异常的代码处理;
}
执行流程:
- 程序从try里面的代码开始执行
- 出现异常,会自动生成一个异常类对象,改异常对象将被提交给Java运行时系统。
- 当Java运行时系统接收到异常对象时,会到catch中去匹配的异常类,找到后进行异常的处理
- 执行完毕之后,程序还可以继续往下执行
修改
修改代码:
public class Main {
public static void main(String[] args) {
System.out.println("开始");
fc();
System.out.println("开始");
}
public static void fc(){
try{
int arr [] = {1, 2, 3, 4};
System.out.println(arr[4]); // 常见的错误之 数组下标访问越界
} catch (ArrayIndexOutOfBoundsException e){
System.out.println("数组下标越界");
}
}
}
运行结果:
Throwable成员方法
printStackTrace()获取错误信息
printStackTrace():打印错误信息。
getMessage()返回throwable的详细消息字符串
public class Main {
public static void main(String[] args) {
System.out.println("开始");
fc();
System.out.println("开始");
}
public static void fc(){
try{
int arr [] = {1, 2, 3, 4};
System.out.println(arr[10]); // 常见的错误之 数组下标访问越界
} catch (ArrayIndexOutOfBoundsException e){
// public String getMessage():返回此throwable的详细消息字符串
System.out.println(e.getMessage());
// 这里返回10代表的是返回的详细的错误信息 就是数组下标访问越界了 越界下标是10
}
/**
* Returns the detail message string of this throwable.
*
* @return the detail message string of this {@code Throwable} instance
* (which may be {@code null}).
*/
// public String getMessage() {
// return detailMessage;
// }
}
}
toString()
throw异常处理
简介:解决的就是try…catch…不能处理的异常。
格式:
throws 异常名
具体例子:
- 最典型的例子就是使用BufferedReader读数据的时候,会用到,特别是我们使用Java写算法题的时候,使用BufferedReader要比使用Scanner读数据快的多。
- 具体的应用场景最直接的就是很多方法,需要throws错误,不然编译不通过,使用idea的话可以自动抛异常。
- 但是如果是下标越界这种问题想要解决的话,还是需要使用try…catch。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException { // 这里抛出IOException错误
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String [] strs = reader.readLine().trim().split(" ");
}
}
抛出异常解决办法:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*; // 这里相当于c++的万能头文件
public class Main{
public static void main(String [] args){
System.out.println("start");
try {
method2();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Compile time exception 编译时异常
public static void method2() throws ParseException{
String s = "2048-08-09";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse(s);
System.out.println(d);
}
}
自定义异常
简介:Java里面可以自定义异常。
学习代码:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*; // 这里相当于c++的万能头文件
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入分数:");
while(true){
int score = in.nextInt();
Teacher teacher = new Teacher();
try {
teacher.checkScore(score);
} catch (ScoreException e){
e.printStackTrace();
}
}
}
public static class ScoreException extends Exception{
public ScoreException(){}
public ScoreException(String message){
super(message);
}
}
public static class Teacher{
// 经典例子之 自定义异常 筛选分数 对于[0,100]以外的抛出异常
public void checkScore(int score) throws ScoreException{
if (score < 0 || score > 100){
throw new ScoreException();
} else {
System.out.println("分数正常");
}
}
}
}
运行结果: