Java异常处理的目的 [英] Purpose of Java Exception Handling

查看:153
本文介绍了Java异常处理的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学习Java异常处理时遇到了以下疑问,



我看到的示例的大多数(几乎全部)都使用try bock和适当的方法抛出异常catch在控制台中向用户打印一条消息,最后阻止用于关闭/释放资源的块。


  1. 异常处理仅是打印消息/导致异常的原因吗?

  2. 同时学习算术例外,我得到的唯一示例是DividebyZero方案,是否有任何其他操作可能导致算术异常?


解决方案

不,异常处理不是要打印消息或引起异常的原因,尽管这些对于弄清为什么首先抛出异常是必不可少的。



异常处理确实更适合我们,因为我们承认在程序的生命周期内可能会发生奇怪的事情,并且根据运行期间出现的怪异事件的类型,我们希望可以从中恢复。 / p>

例如,您的 ArithmeticException 。当应用程序的某些部分决定将某物除以零或出于其他原因(其他类可能会抛出该异常;您必须阅读文档并找出原因)时,会发生这种异常。 Java认为无法从中进行合理的恢复,因此它抛出了运行时异常,或者通常不是要捕获的异常。



我鼓励您查看Oracle的 Exceptions Trail ,因为这将提供有关什么是不同类型的异常的宝贵知识。请注意,如果您的代码中确实存在异常,则最好调查它的原因,而不是捕获它(和/或抑制它)。


I came across below doubts while learning java exception handling,

Most(nearly all) of the example i've seen thows an exception using try bock and the appropriate catch prints a message to the user in the console and finally block used to close/release resources.

  1. Is exception handling is only about printing the message/cause for exception?
  2. While learning arithmetic exception the only example i got is DividebyZero scenario, is there any other operation that can cause arithmetic exception?

解决方案

No, exception handling isn't about printing a message or a cause for exception, although those are essential to figuring out why the exception was thrown in the first place.

Exception handling is really more geared to us acknowledging that weird things can happen during the lifecycle of a program, and depending on the type of "weird thing" that comes up during a run, we can hope to recover from it.

Take, for example, your ArithmeticException. This is an exception which occurs when some part of the application decides to divide something by zero, or for other reasons (other classes may throw this; you'd have to read the documentation and figure out why). Java decides that it can't reasonably recover from that, so it throws a runtime exception, or an exception that isn't typically meant to be caught.

I encourage you to look at the Exceptions Trail from Oracle, as that will provide invaluable knowledge as to what the different types of exceptions are. Just note that, if you do have an exception in your code, it is better to investigate the cause of it, rather than catching it (and/or suppressing it).

这篇关于Java异常处理的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆