4

I built a library/module for a bigger application which throws an Exception from a function. The Exeption is thrown in case the file is not found or file contains bad format.

The method looks something like:

Shape parse(String path) throws Exception {
  // load file, parse file, guild graph

  if ( file does contain bad format ) {
    throw new Exception("bad format");
  }

  parse(newPath); 
}

The exception will terminate my module since it will be caught in the application which uses my module, but that's alright since the format was bad.

What I would like to know is this - is it is a bad practice, throwing Exceptions from recursive functions like that?

Robo Mop
  • 3,485
  • 1
  • 10
  • 23
wxrw
  • 97
  • 2
  • 8
  • 1
    Nope, totally normal practice. I'd say it's better than swallowing (not reporting) the exception or than throwing an unchecked exception. Makes you module easy for others to understand and use. – markspace Apr 10 '18 at 18:45
  • 2
    It is very bad practice to throw a general `Exception`, throw a `BadFormatException` instead. (and declare only that one to be thrown or even make it unchecked) – luk2302 Apr 10 '18 at 18:45
  • 1
    luk actually makes a good point, I assume you were only using `Exception` here as an example, but not in production code. – markspace Apr 10 '18 at 18:47

1 Answers1

4

It really depends on your programming style.

Throwing exceptions inside a recursive function is not bad, but throwing

new Exception("bad format")

is not a very good practice, since it would be hard to catch the specific exception. You should instead create your own exception or use

java.text.ParseException

as a checked exception.

On the other hand, you may also return a Either type to avoid checked exceptions. There are existing answers about implementing it in Java: Is there an equivalent of Scala's Either in Java 8?

Dummyc0m
  • 111
  • 6