Java函数中异常处理的方法及实现
发布时间:2023-06-07 09:54:11
Java异常处理在函数中的方法主要有两种:
1. 抛出异常
当函数中执行到错误的代码时,使用throw语句将异常对象抛出,并将其传递到调用函数的地方,最终交由JVM处理。
例如:
public class Test {
public static void main(String[] args) {
try {
int result = divide(-4, 2);
System.out.println(result);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static int divide(int a, int b) throws Exception {
if (b == 0) {
throw new Exception("除数不能为0");
}
return a / b;
}
}
在上述代码中,函数divide()执行时,如果除数为0,将会抛出一个自定义的异常对象Exception,异常对象会被抛出并交由上层函数或JVM处理。
2. 捕获异常
在函数内部使用try-catch语句捕获异常,当异常发生时,程序会跳转到catch块中执行相应的处理代码。
例如:
public class Test {
public static void main(String[] args) {
int result = divide(4, 0);
System.out.println(result);
}
public static int divide(int a, int b) {
int res = 0;
try {
res = a / b;
} catch (Exception e) {
System.out.println(e.getMessage());
}
return res;
}
}
在上述代码中,函数divide()执行时,如果除数为0,异常会被捕获并跳转到catch块中执行相应的处理代码。
总的来说,抛出异常是将异常交由上层函数或JVM处理,而捕获异常则是在函数内部处理异常。在实际开发中,应根据具体情况选择适当的异常处理方式。
