1、无论如何都会执行finally,即使在catch部分已经return了
但是try-catch后面部门的代码将不执行了(跳出函数)
链接:https://www.nowcoder.com/questionTerminal/ffb26e7e10574ba7b14577f3e328fde7
来源:牛客网
package algorithms.com.guan.javajicu;
public class TestDemo {
public static String output ="";
public static void foo(int i){
try{
if(i == 1){
throw new Exception();
}
}catch(Exception e){
output += "2";
return ;
}finally{
output += "3";
}
output += "4";
}
public static void main(String[] args) {
foo(0);
foo(1);
System.out.println(output); // 3423
}
}
2、再try-catch执行return之后后面的代码不能执行了
如上代码。最后的output += "4"; 不再执行
3、所有的异常类都继承子Throwable类,这个类又有两个子类:Error类以及Exception类,Error属于系统内部错误,不可捕获,会直接导致程序中断,Exception属于可捕获异常,其中有分为运行时异常(数组越界等),属于Java虚拟机生成的异常,非运行时异常(编译时异常如IOException)
4、Java编译器要求Java程序必须捕获或生命所有的非运行时异常如FileNotFoundException/IOException,但是对于运行时异常可以不做处理,因为这种异常很普遍
5、常见异常:
ArithmeticException (被0除)
ArrayIndexOutOfBoundsExcetion (数组下标越界)
NullPointerException (试图用.访问不存在的属性或方法)
NumberFormatException (将非数字字符串转换为字符串) String stage = “34L”; int age = Integer.parseInt(stage);
StringIndexOutOfBoundsException (字符串越界) String name = “jdfjdkfdf”; char ch = name.charAt(name.length());
ArrayStoreException (数组类型不兼容) Object[] b = new Boolean[5]; b[0] = “nihao”;
ClassCastException (描述强制类型转换时的异常) Object obj = new String(“333”); Integer s = (Integer) obj;
6、不能讲子类异常放在父类异常的后面,否则会出错,因为这样永远到达不了子类的Exception,在java中不能到达的代码是一个错误
int numbers[] = new int[3];
try{
numbers[0] = 1;
numbers[2] = numbers[0] / 0;
}catch(Exception e){
System.out.println(e.toString());
}catch(ArithmeticException e){ // 这个catch永远轮不到,编译出错
e.toString();
}
7、为了执行try块中所有的代码,捕获所有可能产生的异常,可以使用嵌套try语句。
public static void main(String[] args) {
String friends[] = {"zhou", "yun", "jin"};
try {
try{
int num = friends.length/0;
}catch(ArithmeticException e){ // 捕获除0异常
e.printStackTrace();
}
for(int i=0;i<=4;i++){
System.out.println(friends[i]);
}
}catch(ArrayIndexOutOfBoundsException e){ // 即使发生了除0异常也可以捕获数组越界异常
e。printStackTarce();
}
}
8、如果一个方法不想在本函数内捕获异常,可以在方法声明后面使用throws可以向上传递异常,由调用它的方法来处理异常
如:
public static int compute(int x) throws ArithmeticException {}
9、可以使用throw来定义一个自定义的异常
10、在try 块中的变量是局部变量,在使用throw语句跑出异常对象时,该语句后面的代码将不会执行,所以,一般情况下throw语句应该放在条件语句里面,或者放到最后面
11、自定义异常类:
(1)创建自定义异常类
(2)在方法中通过throw抛出异常对象
(3)在当前抛出异常的方法中处理异常,使用try。。。catch捕获并且处理。否则在方法的声明处通过throws指明要调用的异常
(4)在出现异常的方法调用代码中捕获并处理的异常