java中Exception的细节-程序员宅基地

技术标签: Java  

[size=x-large]一、异常的丢失[/size]

任何一个Java程序员应该都不会不知道Java中的Exception机制。下面是总结的一些在开发中不是太过于重要的关于Exception的细节。有时候就是因为不注意这些细节而导致一些不易发现的问题。

之前看过一个blog http://blog.csdn.net/hguisu/article/details/6155636 上边有一段代码:

public class TestException {
public TestException() {
}

boolean testEx() throws Exception {
boolean ret = true;
try {
ret = testEx1();
} catch (Exception e) {
System.out.println("testEx, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx, finally; return value=" + ret);
return ret;
}
}

boolean testEx1() throws Exception {
boolean ret = true;
try {
ret = testEx2();
if (!ret) {
return false;
}
System.out.println("testEx1, at the end of try");
return ret;
} catch (Exception e) {
System.out.println("testEx1, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx1, finally; return value=" + ret);
return ret;
}
}

boolean testEx2() throws Exception {
boolean ret = true;
try {
int b = 12;
int c;
for (int i = 2; i >= -2; i--) {
c = b / i;
System.out.println("i=" + i);
}
return true;
} catch (Exception e) {
System.out.println("testEx2, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx2, finally; return value=" + ret);
return ret;
}
}

public static void main(String[] args) {
TestException testException1 = new TestException();
try {
testException1.testEx();
} catch (Exception e) {
e.printStackTrace();
}
}
}

我也掉进了陷阱,选择了:

i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, catch exception
testEx1, finally; return value=false
testEx, catch exception
testEx, finally; return value=false

但是为什么真正的答案是:

i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false

大致浏览了那篇blog写的不错,但是不知浏览太急还是怎么我没找到这个问题的答案,于是就开始翻 thinking in Java 在电子书(已随blog附件上传)的337页找到了答案。

An even simpler way to lose an exception is just to return from inside a finally clause:
//: exceptions/ExceptionSilencer.java
public class ExceptionSilencer {
public static void main(String[] args) {
try {
throw new RuntimeException();
} finally {
// Using ‘return’ inside the finally block
// will silence any thrown exception.
return;
}
}
} ///:~
If you run this program you’ll see that it produces no output, even though an exception is
thrown.

大致是说你在finally中使用return就会屏蔽掉try块和chatch块中抛出的异常,这将会导致异常的丢失。如果不太理解可以设断点单步跟踪一下,那段代码的具体执行路径就不说了。


[size=x-large]二、异常的限制问题[/size]


class MyException extends Exception {

}
class T {
void event() throws MyException {
}
}

public class StormyInning extends T {
@Override
void event() {
}
public static void main(String[] args) {
}
}

这段代码可以通过compiler的正常编译,superclass中方法抛出异常在subclass中覆盖该方法时可以不去抛异常,Java允许在subclass中对异常作出相应处理。如果该方法在superclass和interface中都有相应定义时,就不能再声明抛出什么异常了,否则在使用基类的时候就不能判断是否捕获正确的异常了。

[size=x-large]三、IO处理模板[/size]
IO处理时资源不释放,资源错误释放都会导致应用出现问题,其实IO处理时是有一定模板可以遵循的。

InputStream input = null;
try {
input = new FileInputStream(fileName);
//..process method
} catch (IOException e) {
log.error(e);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
log.error(e);
}
input = null;
}
}



[size=x-large]四、catch异常放置的位置[/size]
父类的catch块,必须放置在子类catch块的下方,以防止子类catch被掩盖。虽然编译器也不允许这种错误发生,在高级IDE,比如eclipse中直接就会以红线标出,但是其中的缘由也是有必要知道的。
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/iteye_18227/article/details/82646738

智能推荐

apksigner完成apk的签名_apksigner 签名-程序员宅基地

文章浏览阅读2.3k次。有时候用第三方加固平台加固以后会让我们重新签名。还有就是上应用市场的时候,如果以前该应用已经在市场上上传过了,由于后面业务原因换了开发者账号再去上传就会提示我们去认领一个没有签名的包(unsign.apk),然后去签名上传进行MD5签名验证,如下图看到上面的提示不要慌,不就是加个签名么,apksigner就是SDK自带的签名工具,处于F:\android-sdk\build-tools\xxx目录下将上面的路径配置到系统环境变量path中,打开cmd,切换到unsign.apk目录下,建议.._apksigner 签名

java内省机制及PropertyUtils使用方法_propertyutils.snaketoline(field.getname());-程序员宅基地

文章浏览阅读1.3k次。背景 一般情况下,在Java中你可以通过get方法轻松获取beans中的属性值。但是,当你事先不知道beans的类型或者将要访问或修改的属性名时,该怎么办?Java语言中提供了一些像java.beans.Introspector这样类,实现了在运行时检测Java类并确定属性get和set方法的名称,结合Java中的反射机制就可以调用这些方法了。然而,这些APIs使用起来比较_propertyutils.snaketoline(field.getname());

LeetCode 516. Longest Palindromic Subsequence--最长回文子序列长度_leetcode longestpalindromesubseq连续字符不想等,长度为偶的回文子序列-程序员宅基地

文章浏览阅读536次。Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.Example 1:Input:"bbbab"Output:4One possible longest palind_leetcode longestpalindromesubseq连续字符不想等,长度为偶的回文子序列长度

Android自定义View之自定义加载进度条(二)-程序员宅基地

文章浏览阅读189次。本文首发于公众号“AntDream”,欢迎微信搜索“AntDream”或扫描文章底部二维码关注,和我一起每天进步一点点自定义加载进度条Android自定义View之手把手带你自定义一个进度条上次我们已经把实线和虚线都绘制好了,这次我们就主要来解决更新的问题:怎么随着时间的推移逐渐地绘制进度条怎么在绘制的过程中加速进度条的绘制首先我们来解决第一个问题,也就是随着时间更新我们的..._setvalueinterpolator

c#判断字符串是否json-程序员宅基地

文章浏览阅读5.7k次。来源:https://www.cnblogs.com/cyq1162/p/3841766.html下载地址:  https://github.com/cyq1162/cyqdata/blob/master/Tool/JsonSplit.cs  https://github.com/cyq1162/cyqdata  using System;using System.C..._c#判断是json还是xml

python读取eml文件并用正则匹配邮箱_python 如何查看eml文件-程序员宅基地

文章浏览阅读992次。python读取eml文件并用正则匹配邮箱_python 如何查看eml文件

随便推点

Jquery插件之DataTables初探_jquery datatables 英文-程序员宅基地

文章浏览阅读2.5k次。今天闲来无事,就研究了一下Jquery的DataTables插件。感觉效果不错,支持排序和内容过滤(查询),在这里向大家推荐一下^_^不得不说之前犯了一个错误,这个插件应该叫做DataTable,而我把它当成了tablesort,实在不好意思。。。。。可以直接到官网上去下载下来,单击http://www.datatables.net/到官网上看看,什么API、demo之类的_jquery datatables 英文

算法:逆序对-程序员宅基地

文章浏览阅读8.5k次,点赞8次,收藏11次。逆序对什么是逆序对呢?百度百科这样解释:设 A 为一个有 n 个数字的有序集 (n>1),其中所有数字各不相同。如果存在正整数 i, j 使得 1 ≤ i < j ≤ n 而且 A[i] > A[j],则 <A[i], A[j]> 这个有序对称为 A 的一个逆序对,也称作逆序数。定义:对于一个包含N个非负整数的数组A[1…n],如果有i < j,且A[ i ]>A[ j ],则称(A[ i] ,A[ j] )为数组A中的一个逆序对。例如,数组(3_逆序对

SLAM导航机器人零基础实战系列:(四)差分底盘设计——3.底盘通信协议_slam 实战-程序员宅基地

文章浏览阅读1.2k次。SLAM+语音机器人DIY系列:(四)差分底盘设计——3.底盘通信协议摘要 运动底盘是移动机器人的重要组成部分,不像激光雷达、IMU、麦克风、音响、摄像头这些通用部件可以直接买到,很难买到通用的底盘。一方面是因为底盘的尺寸结构和参数是要与具体机器人匹配的;另一方面是因为底盘包含软硬件整套解决方案,是很多机..._slam 实战

LOJ #6010. 「网络流 24 题」数字梯形-程序员宅基地

文章浏览阅读89次。#6010. 「网络流 24 题」数字梯形题目描述给定一个由n nn行数字组成的数字梯形如下图所示。梯形的第一行有m mm个数字。从梯形的顶部的m mm个数字开始,在每个数字处可以沿左下或右下方向移动,形成一条从梯形的顶至底的路径。分别遵守以下规则:从梯形的顶至底的m mm条路径互不相交;从梯形的顶至底的m mm..._7-60 数字梯形 (110 分) 给定一个由n行数字组成的数字梯形如下图所示。梯形的第一

Ubuntu20.04 + RTX 3090(兼容RTX 2080 Ti) + Pytorch1.7配置方法_2080ti ubuntr20.04-程序员宅基地

文章浏览阅读2.2k次。背景介绍:由于在Ubuntu16.04系统上安装RTX 3090显卡驱动有点吃力(各种Error和不兼容),使用最新Ubuntu20.04系统搭配最新的RTX 3090显卡配置最新的Pytorch【(*^▽^*)】前期准备: 1、Ubuntu20.04下载:Ubuntu20.4_amd64_desktop.iso 2、UNtebootin光盘刻录软件下载:unetbootin,选择Windows下载 3、NVID..._2080ti ubuntr20.04

Struts + Spring +ibatis 整合开发步骤_struts+spring+ibatis-程序员宅基地

文章浏览阅读329次。一.添加Spring 、Struts框架对web.xml文件的修改1. 添加Spring框架2. 在web.xml中引入Spring配置文件(注意:applicationContext.xml文件的路径)context-param> param-name>contextConfigLocationparam-name> param-v_struts+spring+ibatis