4

I have a class that constructs and returns objects based on certain criteria, each method in the class throws the same exceptions and I would like to reduce the number of times I have to repeat the same:

public Foo getFoo() throws FileNotFoundException, IOException { ... }

Is there a way to declare that each method of a class throws the same set of exceptions?

pxerk
  • 63
  • 1
  • 7
  • 1
    Use the mother of all exceptions. "Exception" – Rod_Algonquin Jun 25 '14 at 21:40
  • 1
    If you *really* find the effort of writing those `throws` clauses to be too much, your class has far too many methods. – Raedwald Jun 25 '14 at 21:52
  • If you want to write DRY code, try to not use Java. – djechlin Jun 25 '14 at 22:06
  • @Raedwald no. this problem can happen for two methods, but if they throw "the same" method it should be DRY. – djechlin Jun 25 '14 at 22:06
  • Just an aside: `FileNotFoundException` **is-a** `IOException`. So declaring only the latter would be sufficient. However, going further up the Hierarchy (declaring "Exception" to be thrown, as mentioned in another comment) is something that I would definietely **NEVER** recommend. People will end with catching `Exception`, and silently swallow any `NullPointerException` that is not caused by an ("expected") IO error, but by a programming error... – Marco13 Jun 25 '14 at 22:40

2 Answers2

6

No there is no way to declare that all methods of particular class throws same set of Exceptions (as of jdk 1.8u5)

jmj
  • 237,923
  • 42
  • 401
  • 438
-3

Well there is no out-of box solution from Microsoft. You can handle exceptions at application level but not at class level.

But there are still ways around to do everything. For example with Custom Attributes, You can create custom attributes yourself

http://msdn.microsoft.com/en-us/library/sw480ze8.aspx

If you don't want to create custom attribute yourself there is a existing library out there to help you out called PostSharp that you can configure using attributes on the methods/class

    [Serializable]
    public class GeneralExceptionAttribute : OnExceptionAspect
    {

        public override void OnException(MethodExecutionArgs args)
        {
            Console.WriteLine(args.Exception.Message);
        }
    }

Then you can also apply the attribute to the whole class, like this:

     [GeneralException]
     public class YourClass 
     {
          // ...
          public string DoSomething(int param) {
                // ...
          }

     }
Tejas Patel
  • 1,289
  • 13
  • 25