try-catch
以下是try-catch块的基本语法:
try {
// 可能抛出异常的代码
} catch (ExceptionType1 e1) {
// 处理ExceptionType1类型的异常
} catch (ExceptionType2 e2) {
// 处理ExceptionType2类型的异常
} finally {
// 可选的finally块,用于执行一些清理操作
}
try-with-resources
使用try-with-resources语句 Java 7引入了try-with-resources语句,用于自动关闭实现了AutoCloseable
接口的资源。在try-with-resources语句中,我们可以在try关键字后面声明一个或多个资源,这些资源将在代码执行完毕后自动关闭。
以下是使用try-with-resources语句的示例代码:
try (Resource1 res1 = new Resource1();
Resource2 res2 = new Resource2()) {
// 使用资源的代码
} catch (ExceptionType e) {
// 处理异常
}
@Data
public class AutoCloseAbleTest implements AutoCloseable {
private boolean closed = false;
@Override
public void close() throws IllegalArgumentException {
closed = true;
throw new IllegalArgumentException("测试抛出异常");
}
public void doSomething(){
System.out.println("现在资源是开着的");
}
}
public class AutoCloseAbleExample {
/**
* 使用try-with-resources模式声明资源
* @param args
*/
public static void main(String[] args){
try(AutoCloseAbleTest test = new AutoCloseAbleTest()){
test.doSomething();
}catch (IllegalArgumentException e){
e.printStackTrace();
}
}
}
执行结果
现在资源是开着的
java.lang.IllegalArgumentException: 测试抛出异常