关于Java异常最常见的八大问题

1.异常管理的最佳做法

如果可以正确处理异常,则应该被捕获,否则应该抛出异常。

2.为什么try中定义的变量不能用于catch或finally?

try {File file = new File(“path”);FileInputStream fis = new FileInputStream(file);String s = “inside”;} catch (FileNotFoundException e) {e.printStackTrace();System.out.println(s);}

原因是你不知道在try块中哪里会抛出异常。在声明对象之前抛出异常是很有可能的。对于这个特定的例子,这是真的。

3.为什么Double.parseDouble(null)和Integer.parseInt(null)会抛出不同的异常?

他们实际上抛出不同的例外 这是JDK的问题。它们由不同的开发人员开发,所以不值得太多思考。

Integer.parseInt(null); // throws java.lang.NumberFormatException: nullDouble.parseDouble(null); // throws java.lang.NullPointerException

4.在Java中常用的运行时异常

这只是其中的一部分。

IllegalArgumentException

ArrayIndexOutOfBoundsException

当条件不满足时,它们可用于if语句中,如下所示:

if (obj == null) { throw new IllegalArgumentException(“obj can not be null”);

5.我们可以在同一个catch子句中捕获多个异常吗?

答案是肯定的。只要这些异常类可以追溯到类继承层次结构中的同一个超类,就可以只使用该超类。

6.构造函数可以在java中引发异常吗?

答案是肯定的。构造函数是一种特殊的方法。这是一个代码示例。

7.在最后条款中抛出异常

执行以下操作是合法的:

public static void main(String[] args) {File file1 = new File(“path1”);File file2 = new File(“path2”);try {FileInputStream fis = new FileInputStream(file1);} catch (FileNotFoundException e) {e.printStackTrace();} finally {try {FileInputStream fis = new FileInputStream(file2);} catch (FileNotFoundException e) {e.printStackTrace();}}}

但为了获得更好的代码可读性,您应该将嵌入式try-catch块作为新方法进行包装,然后将方法调用放在finally子句中。

8.为什么开发人员默默地使用异常?

有很多的时间代码段会发生如下情况。如果正确处理异常非常重要,为什么开发人员仍然这样做?

try { …} catch(Exception e) { e.printStackTrace();}

忽略是很容易的。频繁出现并不意味着正确。

好啦今天的学习文章就到这里了,喜欢就关注一下吧。

文章来源:搜索引擎大全http://www.iis7.com/b/ssyqdq/

猜你喜欢

转载自www.cnblogs.com/ngnntds03/p/10766673.html
今日推荐