Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

  • Always Catch Exceptions

    Wasn't sure if this was to go here or in other. (Mod please move it if it should be somewhere else)

    I have noticed a large amount of posts that are doing something along the lines of
    public static void main(String[] args) throws Exception
    {
     
    }
    The reason that methods throw exceptions, is that the creators of that method believe that the program can still be saved. EG
    /**
     * If the program is in debug mode
     */
    public final boolean DEBUG = true;
    /**
     * Some Instance String
     */
    private String someString;
    /**
     * Get the first line from a file and save it to a variable
     */
    public void getFirstLine(File f)
    {
      try
      {
        BufferedReader in = new BufferedReader(new FileReader(f));
        someString = in.readLine();
        in.close();
      }catch(IOException e)
      {
        if(DEBUG)
        {
          e.printStackTrace():
        }
        System.err.println("An error occured reading the file, setting default properties");
     
        someString = "Yellow Unicorn";
      }
    }


    Here is a quote from the Exception API
    Quote Originally Posted by Exception API
    The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
    Most of the time, if there is an exception, you should (at bare minimum)
    try
    {
      someExceptionThrowingMethod();
    }catch(Exception e)
    {
      e.printStackTrace();
      return;
    }
    What you should never do is
    try
    {
      someExceptionThrowingMethod();
    }catch(Exception e) {}

    When you use an empty catch statement, you are inviting NullPointerException's and other bizarre errors much further along your program, because you caught the exception, but didn't attempt to save the program. Almost all of the time, Exceptions can be handled. Get a FileNotFoundException? Create a default file. Try-Catch statements are not just to make your program messier, they are there to let you handle less-then-optimal situations. If they were expecting everyone to throw their exception because it's program crashing, they would of used a error.

    Quote Originally Posted by Error API
    An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

    A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.
    Many users are attempting to use an Exception like an error. There are many reasonable situations where an Exception would be thrown, whereas if you are getting an error, you seriously screwed up.

    Example of an error, (IOError)

    Quote Originally Posted by IOError API
    Thrown when a serious I/O error has occurred.
    Serious meaning, in this scenario, unrecoverable. I do believe this is thrown if your application is not granting writing permissions and you try to create a file, or the Connection through a network is suddenly interrupted. This does not mean, however, that you cannot catch errors, but it is not recommended.

    The hybrid of errors and exceptions are unchecked exceptions. These include NumberFormatException's, NullPointerException, ArithmeticException, etc. These you can, and are very likely going to catch at some point or the other. NumberFormatException is caught is popular in programs deciding if a String is a number. EG:
    /**
     * @returns 1 if the String is an Integer, 2 if the String is a Long, 3 if the String is a Double, 4 if the String is a
     * BigInteger, and 5 if the Stirng is not a Number.
     */
    public int getType(String theStr)
    {
      try
      {
        Integer.valueOf(theStr);
        return 1;
      }catch(NumberFormatException) //Extends IllegalArgumentException, so does not have to be caught. (IllegalArgumentException extends RuntimeException)
      {
        //Do nothing, not a Integer.
        /*
         * While normally I say that you should never have an empty catch statement,
         * in this scenario it can be expected that an exception will occur.  This
         * is very often the case with unchecked exceptions.
         */
      }
      try
      {
        Long.valueOf(theStr);
        return 2;
      }catch(NumberFormatException)
      {
        //Do nothing, not a Long
      }
      try
      {
        Double.valueOf(theStr);
        return 3;
      }catch(NumberFormatException)
      {
        //Do nothing, not a Double.
      }
      //Check if it is a HUGE number. (BigInteger)
      try
      {
        new BigInteger(theStr);
        return 4;
      }catch(NumberFormatException)
      {
        //Do nothing, not a BigInteger
      }
      //Not a number
      return 5;
    }
    This article was originally published in forum thread: Always Catch Exceptions started by Tjstretch View original post