在Java中,可以使用try-catch语句块来捕获方法中的异常。具体步骤如下:
下面是一个简单的示例代码:
public class MyMethod{ public int divide(int a, int b) throws ArithmeticException { int result = a/b; return result; } }
public class Main{ public static void main(String args[]){ MyMethod myMethod = new MyMethod(); try{ int result = myMethod.divide(10,0); System.out.println(result); }catch(ArithmeticException e){ System.out.println("Division by zero."); }finally{ System.out.println("Done with division."); } } }
在上面的例子中,如果b的值为0,则会抛出ArithmeticException异常,在catch块中进行处理,输出“Division by zero.”。不管异常是否被捕获,finally块中的代码都会被执行,输出“Done with division.”。
上一篇:捕获方法执行时间很长
下一篇:捕获发生百分比