Java Exception
2016-08-30 09:18
323 查看
异常种类
异常体系
try-catch-finally
常见的面试题
throw
出现再try catch finally中的情况
当return出现在try中,并且被执行了(如果return之前发生了异常就是没有被执行)
eg.
调用:
输出:
也就是说,return不影响finally的执行,return的执行过程是:计算return后面的表达式的值,然后压入一个返回栈中,接着去执行finally代码块finally中更改b这个变量并不会影响返回栈中的值。但是如果finally中有return语句的话,之前的返回值就会被抛弃。(相当于又往返回栈中压入了一个新的数据,所以栈顶变了)
eg.
调用:
输出为:
当return出现在catch代码块中和出现在try中的分析过程是一样的,当catch中的return被执行就会先计算return之后表达式的值,然后压入返回栈中,finally中更改return返回的变量的值是不会影响返回栈顶的值的,但是如果在finally中有return语句,那么就是向返回栈中压入了新的数据。
当throw同时出现在try和finally中,并被执行
eg.
此时try中的异常被抑制掉了,也就是被抛弃了,对外只有finally中的异常被抛出
异常体系
try-catch-finally
常见的面试题
异常种类:
Checked Exception:因为用户的原因导致的异常,程序员需要处理 Error:因为系统的原因导致的异常,程序员不需要处理 Runtime Exception:因为程序员的逻辑问题导致的异常,需要处理
异常体系
Throwable |-- Error |-- Exception |-- RuntimeException |-- CheckedException
try-catch-finally
try必须加catch或者finally中的一个 try-with-resource其实就是try-finally,一个语法糖而已
常见的面试题
returnthrow
出现再try catch finally中的情况
当return出现在try中,并且被执行了(如果return之前发生了异常就是没有被执行)
eg.
public static int testException() { int b = 0; try { b = 1; return b; } catch (ArithmeticException e) { System.out.println(b); } finally { System.out.println(b); b=2; } return 0; }
调用:
System.out.println(testException());
输出:
1 1
也就是说,return不影响finally的执行,return的执行过程是:计算return后面的表达式的值,然后压入一个返回栈中,接着去执行finally代码块finally中更改b这个变量并不会影响返回栈中的值。但是如果finally中有return语句的话,之前的返回值就会被抛弃。(相当于又往返回栈中压入了一个新的数据,所以栈顶变了)
eg.
public static int testException() { int b = 0; try { b = 1; return b; } catch (ArithmeticException e) { System.out.println(b); } finally { System.out.println(b); b=2; return b; } }
调用:
System.out.println(testException());
输出为:
1 2
当return出现在catch代码块中和出现在try中的分析过程是一样的,当catch中的return被执行就会先计算return之后表达式的值,然后压入返回栈中,finally中更改return返回的变量的值是不会影响返回栈顶的值的,但是如果在finally中有return语句,那么就是向返回栈中压入了新的数据。
当throw同时出现在try和finally中,并被执行
eg.
public static void testException() throws Exception { try { throw new Exception("exceptionA"); }finally { throw new Exception("exceptionB"); } }
此时try中的异常被抑制掉了,也就是被抛弃了,对外只有finally中的异常被抛出
相关文章推荐
- java exception
- Java Exception
- Java Exception处理之最佳实践
- java Exception: NoClassDefFoundError: org/apache/commons/pool/KeyedObjectPoolFactory
- Java Exception: MISSING EXCEPTION
- Java Exception
- java Exception
- Java Exception
- Java exception
- Java Exception 应用情景(一)
- JAVA Exception 处理
- java exception
- Java exception
- Java Exception
- java exception
- Java Exception性能问题
- Java Exception
- java exception的使用规范
- Java Exception性能问题
- Java Exception