Top 10 Questions about Java Exceptions--reference
reference from:http://www.programcreek.com/2013/10/top-10-questions-about-java-exceptions/ This article summarizes the top 10 frequently asked questions about Java exceptions. 1. Checked vs. Unchecked In brief,checked exceptions must be explicitly caught in a method or declared in the method's throws clause. Unchecked exceptions are caused by problems that can not be solved,such as dividing by zero,null pointer,etc. Checked exceptions are especially important because you expect other developers who use your API to know how to handle the exceptions. For example,IOException is a commonly used checked exception and RuntimeException is an unchecked exception. You can check out the??before reading the rest. 2. Best practice for exception management If an exception can be properly handled then it should be caught,otherwise,it should be thrown. 3. Why variables defined in try can not be used in catch or finally? In the following code,the string s declared in try block can not be used in catch clause. The code does not pass compilation. |
The reason is that you don't know where in the try block the exception would be thrown. It is quite possible that the exception is thrown before the object is declared. This is true for this particular example.
4. Why do Double.parseDouble(null) and Integer.parseInt(null) throw different exceptions?
They actually throw different exceptions. This is a problem of JDK. They are developed by different developers,so it does not worth too much thinking.
5. Commonly used runtime exceptions in Java
Here are just some of them.IllegalArgumentException
ArrayIndexOutOfBoundsException
They can be used in if statement when the condition is not satisfied as follows:
6. Can we catch multiple exceptions in the same catch clause?
The answer is YES. As long as those exception classes can trace back to the same super class in the class inheritance hierarchy,you can use that super class only.
7. Can constructor throw exceptions in java?
The answer is YES. Constructor is a special kind of method.??is a code example.
8. Throw exception in final clause
It is legal to do the following:
But to have better code readability,you should wrap the embedded try-catch block as a new method,and then put the method invocation in the finally clause.
9. Can return be used in finally block
Yes,it can.
10. Why developers consume exception silently?
There are so many time code segments like the following occur. If properly handling exceptions are so important,why developers keep doing that?
Ignoring is just easy. Frequent occurrence does not mean correctness.
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!