用java在try、catch、finally块中分别进行return或throw异常
时间: 2023-12-30 17:05:01 浏览: 24
在Java中,我们可以在try、catch、finally块中分别进行return或throw异常。下面是一些示例代码:
1. 在try块中进行return:
```
public static int divide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
System.out.println("除数不能为0");
} finally {
System.out.println("执行finally块");
}
return -1; // 这里的返回值不会被执行,因为在try块中已经return了
}
```
2. 在catch块中进行return:
```
public static int divide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
System.out.println("除数不能为0");
return -1;
} finally {
System.out.println("执行finally块");
}
}
```
3. 在finally块中进行return:
```
public static int divide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
System.out.println("除数不能为0");
} finally {
System.out.println("执行finally块");
return -1;
}
}
```
4. 在try块中进行throw异常:
```
public static int divide(int a, int b) throws ArithmeticException {
try {
return a / b;
} catch (ArithmeticException e) {
System.out.println("除数不能为0");
throw e;
} finally {
System.out.println("执行finally块");
}
}
```
5. 在catch块中进行throw异常:
```
public static int divide(int a, int b) throws ArithmeticException {
try {
return a / b;
} catch (ArithmeticException e) {
System.out.println("除数不能为0");
throw e;
} finally {
System.out.println("执行finally块");
}
}
```
6. 在finally块中进行throw异常:
```
public static int divide(int a, int b) throws ArithmeticException {
try {
return a / b;
} catch (ArithmeticException e) {
System.out.println("除数不能为0");
} finally {
System.out.println("执行finally块");
throw new ArithmeticException("执行finally块时发生异常");
}
}
```
需要注意的是,如果在try、catch、finally块中都进行了return语句或throw异常语句,那么最终执行的是finally块中的语句。