Java 中的异常和处理
异常
我们在平时编写java程序或者做项目的时候总有时候会遇到各种异常(Exception)或者是错误(error).
异常处理的基本语法
在编写代码处理异常时,对于检查异常,有2种不同的处理方式:使用try…catch…finally语句块处理它。或者,在函数签名中使用throws 声明交给函数调用者caller去解决。
异常分类
Java中将异常分为两大类,第一大类称之为编译时异常(一般异常/检查异常);第二大类称之为运行时异常(RuntimeException)
异常会有很多 有运行时出现异常也有编译异常 比如:
- ArrayIndexOutOfBoundsException
- NullPointerException
- ArithmeticException
- ClassCastException
- FileNotFoundException
- IOException
- ClassNotFoundException
- ParseException
异常的处理
异常的处理可以有抛出(throw)和捕获(catch)。
在编写代码处理异常时,对于检查异常,有2种不同的处理方式:使用try…catch…finally语句块处理它。或者,在函数签名中使用throws 声明交给函数调用者caller去解决。
基本语法:
try{
}catch(Exception exception){
}finally{
}
异常抛出:通常使用throws
public class Demo2 {
/**方法抛出了异常,将由下一级调用者处理*/
public void m1() throws FileNotFoundException{
FileInputStream fis = new FileInputStream("c:/a.txt");
}
/**该方法调用了m1方法,因此需要处理m1中的异常,另外:m2方法可以抛出比m1方法范围更大的异常*/
public void m2() throws IOException{
System.out.println("第二个方法");
m1();
}
/**检查异常最终可以抛给主方法由JVM进行最终处理(打印异常信息到标准输出流)*/
public static void main(String[] args) throws IOException{
new Demo2().m2();
}
}
自定义异常:
必须是自定义类继承Exception
继承Exception原因:
异常体系有一个特点:因为异常类和异常对象都被抛出。他们都具备可抛性,这个可抛性是Throwable这个体系中独有特点。
public class TestAccount {
public void change(Account a,Account b,double cash) throws hplessException{
if(a.gethp() < cash){
//余额不足
throw new hplessException(1, "生命值不足");
}
}
public static void main(String[] args) throws hplessException {
Account a = new Account(1,30000);
Account b = new Account(1,500);
new TestAccount().change(a, b, 35000);
}
}
注意事项
注意出现异常的类型。
注意异常出现的关键字。