Java中异常处理机制示例

原创 雨点打透心脏的1/2处 2024-11-25 17:51 119阅读 0赞

在Java中,异常处理机制主要通过try、catch和finally关键字来实现。以下是一个简单的示例:

  1. public class ExceptionHandlingExample {
  2. public static void main(String[] args) {
  3. // 创建一个可能会抛出异常的对象
  4. try {
  5. int divisionResult = 10 / 2; // 这个操作会导致ArithmeticException
  6. System.out.println("Division result: " + divisionResult);
  7. } catch (ArithmeticException e) { // 这里捕获了ArithmeticException
  8. System.out.println("An ArithmeticException occurred: " + e.getMessage());
  9. } finally {
  10. System.out.println("This is the finally block. It always executes, regardless of whether an exception was caught or not.");
  11. }
  12. }
  13. }

在这个示例中,我们尝试进行一个除法操作,但因为除数为0,这会导致ArithmeticException。我们在try块中捕获这个异常,并在catch块中打印错误信息。最后,无论是否发生异常,finally块中的代码都会被执行。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,119人围观)

还没有评论,来说两句吧...

相关阅读