简体   繁体   English

你抛出什么样的异常?

[英]What kind of Exception do you throw?

I have a method which searches for a variable in the Environment first, and if it isn't found there it searches config.properties .我有一个方法,它首先在 Environment 中搜索一个变量,如果在那里找不到它,它会搜索config.properties If neither yield a result, what Exception do you throw?如果两者都没有产生结果,你会抛出什么异常?

NotFoundException sounds perfect, except it's used for when a resource isn't found on a server. NotFoundException听起来很完美,但它用于在服务器上找不到资源时使用。

So what, then, RuntimeException(String msg) and clarify in the message?那么, RuntimeException(String msg)并在消息中澄清什么?

However, upon reading Unchecked Exceptions — The Controversy I read that if a client can recover from the exception (they could elect to set a default value or something else), I should use a Checked Exception.但是,在阅读Unchecked Exceptions — The Controversy时,我读到如果客户端可以从异常中恢复(他们可以选择设置默认值或其他内容),我应该使用 Checked Exception。 Going through a list of exceptions I can't find a suitable one, so then I assume I should throw Exception ?浏览一个异常列表,我找不到合适的,所以我假设我应该抛出Exception

Did I answer my own question?我回答了我自己的问题吗?

Only in the rarest cases would I throw a predefined exception from my application code.只有在极少数情况下,我才会从我的应用程序代码中抛出一个预定义的异常。 Usually I define my own exception, much like @Edwin Dalorzo suggests.通常我定义自己的例外,就像@Edwin Dalorzo 建议的那样。 This gives you more fine-grained control in the higher layers of your application to decide what to do about it.这使您可以在应用程序的更高层中进行更细粒度的控制,以决定如何处理它。 The least I do is have two different types, one for things that are fatal (ie failures I can not handle inside the application) and recoverable failures (ie failures the application can deal with).我至少有两种不同的类型,一种是致命的(即我无法在应用程序内部处理的故障)和可恢复的故障(即应用程序可以处理的故障)。 Example: If your application can not run without that configuration variable, it is a fatal case that you let bubble up to the outer layer of your application (ie the Controller in web application or web service).示例:如果您的应用程序在没有该配置变量的情况下无法运行,那么您让冒泡到应用程序的外层是致命的情况(即 web 应用程序或 Z2567A5EC9705EB7AC2C984033E0618DZ 服务中的 Controller)。 If some higher layer could work without that variable, it is not fatal.如果某个更高层可以在没有该变量的情况下工作,那么它不是致命的。 The main difference is: Should the application itself deal with it or only the outer-most layer?主要区别在于:应用程序本身应该处理它还是只处理最外层?

Consider creating an exception that extends RuntimeException.考虑创建一个扩展 RuntimeException 的异常。 For example, public class BlamException extends RuntimeException... (name it something meaningful like "BadConfigurationException").例如, public class BlamException extends RuntimeException... (将其命名为有意义的名称,例如“BadConfigurationException”)。

Much of the RuntimeException "controversy" is just goofballs claiming that the program can recover from an unexpected, invalid state which is usually (perhaps just often) not the case.许多 RuntimeException “争议”只是愚蠢的声称程序可以从意外的无效 state 中恢复,而这通常(可能只是经常)并非如此。 In the case of a missing configuration value, there is likely no good default value.在缺少配置值的情况下,可能没有好的默认值。

If you are going to allow default values, then implement a default value for the missing configuration value and log a message stating something like "Warning: Configuration value blam is missing. Using default value: kapow".如果您要允许默认值,则为缺少的配置值实施默认值并记录一条消息,说明“警告:缺少配置值 blam。使用默认值:kapow”。

100% you should not use a Checked Exception. 100% 你不应该使用 Checked Exception。 A Checked Exception requires the program to catch and "handle" the exception. Checked Exception 要求程序捕获并“处理”异常。 In your case, the "handle" part is "prevent the application from starting", which will happen if you throw a RuntimeException.在您的情况下,“句柄”部分是“阻止应用程序启动”,如果您抛出 RuntimeException,就会发生这种情况。

How about NoSuchElementException : NoSuchElementException怎么样:

Thrown by various accessor methods to indicate that the element being requested does not exist.由各种访问器方法抛出以指示所请求的元素不存在。

I have a method that searches for a variable in the Environment first, and if it isn't found there it searches config.properties.我有一个方法,它首先在环境中搜索变量,如果在那里找不到它,它会搜索 config.properties。 If neither yield a result如果两者都没有产生结果

Doesn't this sound just perfect for defining your own Exception ?这听起来不是很适合定义你自己的Exception吗? Let us take a situation here:让我们在这里看一个情况:

You are developing an application for bank and you want to verify if the user says A who wants to send money to another user say B您正在为银行开发应用程序,并且您想验证用户是否说A想要向另一个用户汇款的用户说B
So before transferring money, we would check whether A has that much amount, and if he/she has then we will carry forward the transaction.所以在转账之前,我们会检查A是否有这么多的金额,如果他/她有那么我们将继续交易。
What is A doesn't have that much balance?什么是A没有那么多平衡? As a responsible developer, you will notify A .作为负责任的开发人员,您将通知A Here there are many ways to deal with it.这里有很多方法来处理它。 But what I would prefer here is Defining my own exception.但我更喜欢在这里定义我自己的例外。 InsufficentBalanceException(int amount) . InsufficentBalanceException(int amount)

You could use a unchecked exception by writing a wrapper class which would extend RuntimeException class with a custom message in case you're dealing with resources.您可以通过编写包装器 class来使用未经检查的异常,如果您正在处理资源,它将使用自定义消息扩展RuntimeException class

Overall you need to propagate the Exception to application level, because configuration does matter while starting you application.总体而言,您需要将异常传播到应用程序级别,因为在启动应用程序时配置确实很重要。

Example例子

ErrorClass.java ErrorClass.java

public type doSomething(){
...
...
try{
   ...
} catch(FileNotFoundException e){
throw new MyCustomFileNotFoundException("config file not found", e); // no destructive wrapping here
}
}

MyCustomFileNotFoundException.java MyCustomFileNotFoundException.java

public class MyCustomFileNotFoundException extends RuntimeException{
    public MyCustomFileNotFoundException(String msg, Throwable cause){
    super(msg, cause);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM