Unhandled exception type Exception

后端 未结 2 1831
情书的邮戳
情书的邮戳 2021-01-28 01:17

This is a simplified class that describes my problem:

public class Main {

    enum Test{
        First(method()){ // Unhandled exception type Exception
                 


        
2条回答
  •  不思量自难忘°
    2021-01-28 01:54

    I don't think you want to be throwing a checked exception here (which is what Exception is). The reason: you're invoking the call of method inside of the constructor of Test. There's really not a clean way to deal with it.

    While the obvious choice here is to switch to RuntimeException, I want you to reconsider throwing the exception in the first place. Since your enum will only ever have First declared in it, does it really make sense for it to throw an exception when it's being instantiated? Personally, I don't think it does; whatever dangerous operation it's doing should be deferred until you want to invoke it, and then would you want to throw your exception.

提交回复
热议问题