Java语言之异常与捕获
1.异常之间的关系:
如上图可知:所有异常都是通过继承Throwable而来的.
1.Error:描述java运行时的内部错误和资源耗尽的错误,程序不抛出异常,若出现此现象,程序会安全终止并告知用户
2.Exception:异常如图又分为IOException与RuntimeException.一般由于程序错误的异常称为RuntimeException
I/O错误导致的问题,称为IOException.
注:非受查异常:Error RuntimeException. 其余一般为受查异常.
异常实例如下:
public class Test {
public static void main(String[] args) {
System.out.println(10/0);//0不可以做除数,会出现异常
}
}
2.异常处理的格式:
try{
}catch(异常类 对象){
}finally{
异常出口
}
注:上图三个关键字可以组合为: try...catch try...finally try...catch...finally
示例如下:
public class Test {
public static void main(String[] args) {
try {
System.out.println(10 / 0);//0不可以做除数,会出现异常
}catch(ArithmeticException e){
e.printStackTrace();//打印对应的异常情况
System.out.println("异常处理了");
}finally {
System.out.println("结束了");
}
}
}
注:无论是否产生异常,finally对应的代码最终都会执行,所以finall被称为程序的出口.
举例:
public class Test {
public static void main(String[] args) {
System.out.println(Add(10,2));
}
public static int Add(int x,int y){
try{
int c = x+y;
return c;
}finally {
return 10;
}
}
对应结果为:
由上图可知:若finally中存在return,会先执行finally的内容.
3.throws关键字
throws:在进行方法定义时,若要告诉调用者本方法可能产生哪些异常,就可以使用throws关键字.
示例如下:
public class Test {
public static void main(String[] args) {
try{
System.out.println(calculate(10,0));
}catch (Exception e){
e.printStackTrace();
}
}
public static int calculate(int x,int y)throws Exception{
return x/y;
}//throws定义方法
}
注:如果调用了throws声明的方法,在调用的时候必须明确使用try...catch进行捕获.因为该方法可能产生异常,需要按照异常方式处理.
若在主方法上使用throws进行异常捕获,就会将产生的异常交给JVM来处理.
4.throw关键字
throw:编写在语句中,是通过人为进行异常抛出的,若我们不希望JVM产生异常类对象,就可以通过throw关键字
示例如下:
public class Test {
public static void main(String[] args) {
try {
throw new Exception();
}catch (Exception e){
e.printStackTrace();
}
}
}
注:throws与throw的区别?
1.throws主要在方法上使用,明确告诉用户方法产生的异常,同时该方法可能不处理异常;
2.throw主要用于方法内部,表示手工抛出异常.
注:Exception与RuntimeException的区别?
1.Exception是 RuntimeException的父类,Exception对应的异常都必须处理,而RuntimeException异常可以根据用户的选择来进行相应的处理.
2.常见的RuntimeException类型异常有:ClassCastException NullPointerExcep.
5.自定义异常类
在java中,在很多时候异常信息不够我们使用时,我们就可以采用自定义异常.
注:自定义异常可以继承两种父类:Exception RuntimeException
示例如下:
package test;
class AddException extends Exception{
public AddException(String msg){
super(msg);
}
}
public class Test{
public static void main(String[] args) throws AddException {
int a = 20;
int b = 30;
if(a+b==50){
throw new AddException("出错");
}
}
}
综合练习题:
实现:1.进行除法计算操作前打印一行**;
2.出现异常时,将异常返回调用处
3.最终必须打印一行结果;
练习代码如下:
package test;
public class Test{
public static void main(String[] args) {
try {
System.out.println(calculate(10,0));
}catch (Exception e){
e.printStackTrace();//打印异常
}
}
public static int calculate(int x ,int y)throws Exception{
int result = 0;
System.out.println("***********");
try {
result = x/y;
}catch (Exception e){
throw e;//抛出去
}finally {
System.out.println("结束");
}
return result;
}
}