当finally和return一起出现时的情况
当finally和return一起出现时的情况:
(1)情况一:finally里面有return,结果就是返回finally中的
(2)情况二:finally里面没有return,结果就是返回try或catch中的
说明:一般情况下不建议在finally中写return,因为写了return其他的return就没有用了
public class TestFinallyReturn_5 {
public static void main(String[] args) {
System.out.println(getNum());
System.out.println(getInt());
}
public static int getNum() {
int i = 10;
try {
i = 20;
System.out.println("try");
return i;
} catch (Exception e) {//无异常
i = 30;
System.out.println("catch");
return i;
} finally {
i = 40;
System.out.println("finally");
return i;
}
}
public static int getInt() {
int i = 10;
try {
i = 20;
System.out.println("try i = " + i);
return i;
} catch (Exception e) {//无异常
i = 30;
System.out.println("catch");
return i;
} finally {
i = 40;
//i已经变为了40为什么返回的还是20呢
System.out.println("finally i = " + i);
}
}
}
throws
用在声明一个**方法时**,明确声明该方法可能会抛出XXX异常。
**说明这些异常在该方法中没有try...catch,由调用者处理**
语法格式:
【修饰符】 返回值类型 方法名(【形参列表】)【throws 异常列表】{}
说明:throws后面可以加好几个异常,顺序无所谓,一般如果有父类的异常,子类异常就不写了
public class TestThrows_6 {
public static void main(String[] args) {
try {
//Exception是编译时异常,直接红线报错,让你立马处理
//ArithmeticException这个异常时运行时异常,不会让你立马处理
divide(3,2);
} catch (ArithmeticException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//可以一次性的写好几个异常
public static int divide(int a,int b)throws ArithmeticException,Exception{
return a/b;
}
}
throws与方法重写
方法重写(Override)的要求:
(1)方法名:必须相同
(2)形参列表:必须相同
(3)返回值类型:
基本数据类型和void:必须相同
引用数据类型:<=
(4)权限修饰符:>=
(5)抛出的异常列表的类型:<=
两同两小一大
public class TestThrows2_7 {
}
class Father{
public Object test() throws Exception{
System.out.println("父类的");
return null;
}
}
class Son extends Father {
public String test() throws RuntimeException{
System.out.println("子类的");
return "";
}
}