当Exception类可以处理所有类型的异常时,需要其他异常类? [英] What is the need of other Exception classes when Exception class alone can handle all type of exceptions?

查看:178
本文介绍了当Exception类可以处理所有类型的异常时,需要其他异常类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一次采访中,面试官问我有关多个 catch 块的问题。问题是:为什么我们需要 Exception 的其他子类来处理异常,如果父类,即异常,单独可以处理所有其他异常。

In one of my interviews the interviewer asked me a question about multiple catch blocks. The question was: Why do we need other child classes of Exception to handle the exception, if the parent class, that is, Exception, alone can handle all other exceptions.

推荐答案

使用自写子类的异常或RuntimeException有不同的优点:

There are different advantages of using self written subclasses of Exception or RuntimeException:


  • 您可以将其他信息(字段)添加到您交给记录的异常中。这可以帮助您更轻松地跟踪您的错误,或者为用户提供更多信息,如果他的应用程序崩溃,他可以为您提供更多信息。

  • 您可以更轻松地区分不同的错误原因,因此决定如何解决不同的错误情况(例如,如果您输入的参数有误,您可以使用IllegalArgumentException,以便您可以提示用户输入有效的参数;另一方面,IOException表示您无法读取/写入数据全部)

这篇关于当Exception类可以处理所有类型的异常时,需要其他异常类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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