I came across a code base that reads text files and parses them. I’m a little confused about how exceptions are used. AppFileReaderException The extends defines an exception where the extended class only returns an error message for the exception. In addition, the getSymbol() function uses both throws and try and catch blocks. This error() function also has an exception handler, which can cause nested exceptions! Is there any benefit to performing such exception handling when basic try and catch should be sufficient? Is there any reason to extend the exception class to bring the two together? Throws and try-catch blocks? Are these excessive killings or are they structured for good reason?

package AppName;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

public class AppFileReader {

    //
    public char getSymbol(a) throws AppFileReaderException {
        try {

        //do something

       } catch (Exception e) {
            error("IO Error: " + fileName + "@" + currentLineNumber);
        }
        return somechar;
    }

    public void error(String errorMsg) throws AppFileReaderException {
        throw new AppFileReaderException(errorMsg);
    }

    public AppFileReader(String fileName) throws FileNotFoundException {
        reader = new LineNumberReader(new FileReader(fileName));
        this.fileName = fileName; }}Copy the code

Class extension of class. AppFileReaderException is as follows:

package AppName;
public class AppFileReaderException extends Exception {

    public AppFileReaderException(String msg)
    { super(msg); }}Copy the code

First, the error() method (not a function!) There is no processing. It simply throws an exception with the given message.

It can be useful to create your own exception class when calling a method; Therefore, you can do the following

public void methodThatCallsLibrary(a) {
   try {
      doSomething();
      new AppFileReader().getSymbol();
      doOtherSomething();
   } catch (AppFileReaderException afre) {
     // handling specific to appFileReader
   } catch (Exception e) {
      // handling related to the rest of the code.}}Copy the code

In other words, the system here is a little strange. With the error() method, the stack trace of an exception is the same for all possible locations where the exception was raised. Also, it looks like it just masks IOException, so I might forward IOException itself (if not, include nested exceptions in the final exception thrown to provide better debugging information).