受检异常
非受检异常
注意
private static void readFile(String filePath) throws IOException {
File file = new File(filePath);
String result;
BufferedReader reader = new BufferedReader(new FileReader(file));
while((result = reader.readLine())!=null) {
System.out.println(result);
}
reader.close();
}
private static void readFile(String filePath) throws MyException {
try {
// code
} catch (IOException e) {
MyException ex = new MyException("read file failed.");
ex.initCause(e);
throw ex;
}
}
private static void readFile(String filePath) {
try {
// code
} catch (FileNotFoundException e) {
// handle FileNotFoundException
} catch (IOException e){
// handle IOException
}
}
private static void readFile(String filePath) {
try {
// code
} catch (FileNotFoundException | UnknownHostException e) {
// handle FileNotFoundException or UnknownHostException
} catch (IOException e){
// handle IOException
}
}
public class MyException extends Exception {
public MyException(){ }
public MyException(String msg){
super(msg);
}
// ...
}
private static void readFile(String filePath) throws MyException {
File file = new File(filePath);
String result;
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
while((result = reader.readLine())!=null) {
System.out.println(result);
}
} catch (IOException e) {
System.out.println("readFile method catch block.");
MyException ex = new MyException("read file failed.");
ex.initCause(e);
throw ex;
} finally {
System.out.println("readFile method finally block.");
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
catch (IOException e) {
System.out.println("readFile method catch block.");
return;
}
readFile method catch block.
readFile method finally block.
private static void tryWithResourceTest(){
try (Scanner scanner = new Scanner(new FileInputStream("c:/abc"),"UTF-8")){
// code
} catch (IOException e){
// handle exception
}
}
throws 关键字和 throw 关键字在使用上的几点区别如下:
原因
代码示例1:
public static int getInt() {
int a = 10;
try {
System.out.println(a / 0);
a = 20;
} catch (ArithmeticException e) {
a = 30;
return a;
/*
* return a 在程序执行到这一步的时候,这里不是return a 而是 return 30;这个返回路径就形成了
* 但是呢,它发现后面还有finally,所以继续执行finally的内容,a=40
* 再次回到以前的路径,继续走return 30,形成返回路径之后,这里的a就不是a变量了,而是常量30
*/
} finally {
a = 40;
}
return a;
}
public static int getInt() {
int a = 10;
try {
System.out.println(a / 0);
a = 20;
} catch (ArithmeticException e) {
a = 30;
return a;
} finally {
a = 40;
//如果这样,就又重新形成了一条返回路径,由于只能通过1个return返回,所以这里直接返回40
return a;
}
}
try {
throw new ExampleB("b")
} catch(ExampleA e){
System.out.println("ExampleA");
} catch(Exception e){
System.out.println("Exception");
}
class Annoyance extends Exception {
}
class Sneeze extends Annoyance {
}
class Human {
public static void main(String[] args) throws Exception {
try {
try {
throw new Sneeze();
} catch ( Annoyance a ) {
System.out.println("Caught Annoyance");
throw a;
}
} catch ( Sneeze s ) {
System.out.println("Caught Sneeze");
return ;
} finally {
System.out.println("Hello World!");
}
}
}
Caught Annoyance
Caught Sneeze
Hello World!
当使用类似InputStream这种需要使用后关闭的资源时,一个常见的错误就是在try块的最后关闭
资源。
public void doNotCloseResourceInTry() {
FileInputStream inputStream = null;
try {
File file = new File("./tmp.txt");
inputStream = new FileInputStream(file);
// use the inputStream to read a file
// do NOT do this
inputStream.close();
} catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
}
}
所以,你应该把清理工作的代码放到 finally 里去,或者使用 try-with-resource 特性。
1.1 使用 finally 代码块
public void closeResourceInFinally() {
FileInputStream inputStream = null;
try {
File file = new File("./tmp.txt");
inputStream = new FileInputStream(file);
// use the inputStream to read a file
} catch (FileNotFoundException e) {
log.error(e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error(e);
}
}
}
}
1.2 Java 7 的 try-with-resource 语法
public void automaticallyCloseResource() {
File file = new File("./tmp.txt");
try (FileInputStream inputStream = new FileInputStream(file);) {
// use the inputStream to read a file
} catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
}
}
public void doNotDoThis() throws Exception {
...
}
public void doThis() throws NumberFormatException {
...
}
public void doSomething(String input) throws MyBusinessException {
...
}
try {
new Long("xyz");
} catch (NumberFormatException e) {
log.error(e);
}
public void catchMostSpecificExceptionFirst() {
try {
doSomething("A message");
} catch (NumberFormatException e) {
log.error(e);
} catch (IllegalArgumentException e) {
log.error(e)
}
}
public void doNotCatchThrowable() {
try {
// do something
} catch (Throwable t) {
// don't do this!
}
}
public void doNotIgnoreExceptions() {
try {
// do something
} catch (NumberFormatException e) {
// this will never happen
}
}
public void logAnException() {
try {
// do something
} catch (NumberFormatException e) {
log.error("This should never happen: " + e);
}
}
这可能是本文中最常被忽略的最佳实践。可以发现很多代码甚至类库中都会有捕获异常、记录日志
并再次抛出的逻辑。如下:
try {
new Long("xyz");
} catch (NumberFormatException e) {
log.error(e);
throw e;
}
17:44:28,945 ERROR TestExceptionHandling:65 - java.lang.NumberFormatException:
For input string: “xyz”
Exception in thread “main” java.lang.NumberFormatException: For input string:“xyz”
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.(Long.java:965)
at
com.stackify.example.TestExceptionHandling.logAndThrowException(TestExceptionHandling.java:63)
at
com.stackify.example.TestExceptionHandling.main(TestExceptionHandling.java:58)
public void wrapException(String input) throws MyBusinessException {
try {
// do something
} catch (NumberFormatException e) {
throw new MyBusinessException("A message that describes the error.", e);
}
}
因此,仅仅当想要处理异常时才去捕获,否则只需要在方法签名中声明让调用者去处理。
public void wrapException(String input) throws MyBusinessException {
try {
// do something
} catch (NumberFormatException e) {
throw new MyBusinessException("A message that describes the error.", e);
}
}
private int x = 0;
public int checkReturn() {
try {
// x等于1,此处不返回
return ++x;
} finally {
// 返回的结果是2
return ++x;
}
}
史上最全Java面试宝典,BAT大厂面试必备。整理不易,建议先关注点赞加收藏
序号 | 名称 | 地址 |
---|---|---|
1 | Java基础面试题(91道含答案) | (点击查看) |
2 | Java并发编程面试题 (123道含答案) | (点击查看) |
3 | Java异常面试题 (33道含答案) | (点击查看) |
4 | Java虚拟机(JVM)面试题(51道含答案) | (点击查看) |
5 | Java集合面试题(52道含答案) | (点击查看) |
6 | Linux面试题(50道含答案) | (点击查看) |
7 | Memcache面试题(23道含答案) | (点击查看) |
8 | Mybatiss面试题 (37道含答案) | (点击查看) |
9 | MySQL面试题(40道含答案) | (点击查看) |
10 | Netty面试题(49道含答案) | (点击查看) |
11 | Nginx面试题(23道含答案) | (点击查看) |
12 | RabbitMQ面试题(22道含答案) | (点击查看) |
13 | Redis面试题(70道含答案) | (点击查看) |
14 | SpringBoot面试题(44道含答案) | (点击查看) |
15 | SpringCloud面试题(49道含答案) | (点击查看) |
16 | SpringMVC面试题(29道含答案) | (点击查看) |
17 | Spring面试题(75道含答案) | (点击查看) |
18 | TCP、UDP、Socket、Http网络编程面试题(47道含答案) | (点击查看) |
19 | Tomcat面试题(15道含答案) | (点击查看) |
20 | Zookeeper面试题(28道含答案) | (点击查看) |
21 | 多线程面试题(60道含答案) | (点击查看) |
22 | 设计模式面试题(14道含答案) | (点击查看) |
23 | BIO、NIO、AIO、Netty面试题(35道含答案) | (点击查看) |
24 | Dubbo面试题(47道含答案) | (点击查看) |
25 | ElasticSearch面试题(31道含答案) | (点击查看) |
26 | Git常用命令(63条) | (点击查看) |