了解java异常就要知道什么是异常
异常是导致程序的正常流程被中断的事件
比如要打开C盘的test.txt文件,这个文件是有可能不存在的
Java中通过 new FileInputStream(f) 试图打开某文件,就有可能抛出文件不存在异常FileNotFoundException
如果不处理该异常,就会有编译错误
import java.io.File;
import java.io.FileInputStream;
public class TestException {
public static void main(String[] args) {
File f= new File("c:/test.txt");
//试图打开文件test.txt,会抛出FileNotFoundException,如果不处理该异常,就会有编译错误
new FileInputStream(f);
}
}
除了这个中文件找不到的异常,我们常见还有可能出现空指针异常,数组越界的异常等。
java中如何处理异常
异常处理常见手段: try catch finally throws
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class TestException {
public static void main(String[] args) {
File f= new File("c:/test.txt");
try{
System.out.println("试图打开 c:/test.txt");
new FileInputStream(f); //成功就会执行下面的打开成功,否则会抛出异常,然后在catch中被接收处理
System.out.println("成功打开");
}
catch(FileNotFoundException e){
System.out.println("c:/test.txt不存在");
e.printStackTrace();
}
}
}
也可以用FileNotFoundException的父类Exception来catch住FileNotFoundException异常,只需要将catch(FileNotFoundException e)改为catch(Exception e)
上面的例子只有一个异常,那么如果出现多个异常的情况呢?
例子
方法一:
public class TestException {
public static void main(String[] args) {
File f = new File("c:/test.txt");
try {
System.out.println("试图打开 c:/test.txt");
new FileInputStream(f);
System.out.println("成功打开");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse("2020-03-03");
} catch (FileNotFoundException e) {
System.out.println("c:/test.txt不存在");
e.printStackTrace();
} catch (ParseException e) {
System.out.println("日期格式解析错误");
e.printStackTrace();
}
}
}
方法二
public class TestException {
public static void main(String[] args) {
File f = new File("d:/LOL.exe");
try {
System.out.println("试图打开 c:/test.txt");
new FileInputStream(f);
System.out.println("成功打开");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse("2020-03-03");
} catch (FileNotFoundException | ParseException e) {
if (e instanceof FileNotFoundException)
System.out.println("c:/test.txt不存在");
if (e instanceof ParseException)
System.out.println("日期格式解析错误");
e.printStackTrace();
}
}
}
这种方式从 JDK7开始支持,好处是捕捉的代码更紧凑,不足之处是,一旦发生异常,不能确定到底是哪种异常,需要通过instanceof 进行判断具体的异常类型
上边的例子和讲解是基本的异常的处理情况,那么我们需要了解异常的的分类及如何自定义异常
总体上异常分三类:
- 错误
- 运行时异常
- 可查异常
可查异常: CheckedException
可查异常即必须进行处理的异常,要么try catch住,要么往外抛,谁调用,谁处理,比如 FileNotFoundException
如果不处理,编译器,就不让你通过。上面的几个例子就是可查异常
运行时异常RuntimeException指: 不是必须进行try catch的异常
常见运行时异常:
除数不能为0异常:ArithmeticException
下标越界异常:ArrayIndexOutOfBoundsException
空指针异常:NullPointerException
在编写代码的时候,依然可以使用try catch throws进行处理,与可查异常不同之处在于,即便不进行try catch,也不会有编译错误
Java之所以会设计运行时异常的原因之一,是因为下标越界,空指针这些运行时异常太过于普遍,如果都需要进行捕捉,代码的可读性就会变得很糟糕。
public class TestException {
public static void main(String[] args) {
//任何除数不能为0:ArithmeticException
int k = 5/0;
//下标越界异常:ArrayIndexOutOfBoundsException
int j[] = new int[5];
j[10] = 10;
//空指针异常:NullPointerException
String str = null;
str.length();
}
}
错误Error,指的是系统级别的异常,通常是内存用光了
在默认设置下,一般java程序启动的时候,最大可以使用16m的内存
如例不停的给StringBuffer追加字符,很快就把内存使用光了。抛出OutOfMemoryError
与运行时异常一样,错误也是不要求强制捕捉的
public class TestException {
public static void main(String[] args) {
StringBuffer sb =new StringBuffer();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
sb.append('a');
}
}
}
上面讲述的三类异常,那么我们如何根据我们的需求来自定异常
例子:Account这个类涉及到几个处理方法,获取当前金额、存款、取款。在我们日常生活中前两个方法是不会出现什么问题的。问题是在取钱的时候,如果输入取钱的金额大于余额,是不是应该返回个异常,然后处理这个异常
public class Account {
private double balance = 1000;
public double getBalance() {
return balance;
}
public void deposit(double balance){
this.balance = balance+this.balance;
}
public void withdraw(double balance) throws OverdraftException{
if(balance>this.balance){
throw new OverdraftException(balance-this.balance);
}
this.balance = this.balance-balance;
}
//在当前类中自定义异常
class OverdraftException extends Exception{
private double deficit;
public OverdraftException(double deficit){
this.deficit = deficit;
}
public double getDeficit(){
return deficit;
}
}
public static void main(String[] args) {
Account account = new Account();
System.out.println(account.getBalance());
account.deposit(100);
System.out.println(account.getBalance());
try {
account.withdraw(10000);
System.out.println(account.getBalance());
}catch (OverdraftException e){
System.out.println(e.getDeficit());
}
}
}
以上就是简单的异常的介绍以及处理