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.

Results 1 to 3 of 3

Thread: Always Catch Exceptions

  1. #1
    Forum VIP
    Join Date
    Oct 2010
    Posts
    275
    My Mood
    Cool
    Thanks
    32
    Thanked 54 Times in 47 Posts
    Blog Entries
    2

    Default 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;
    }
    Last edited by Tjstretch; October 26th, 2011 at 10:55 AM. Reason: typo

  2. The Following 3 Users Say Thank You to Tjstretch For This Useful Post:

    copeg (October 27th, 2011), JavaPF (October 27th, 2011), william (October 26th, 2011)


  3. #2
    Member
    Join Date
    Oct 2011
    Posts
    42
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default Re: Always Catch Exceptions

    Thanks for a good article!

    java exception
    Last edited by hns1984; January 11th, 2012 at 05:53 PM.

  4. #3
    Super Moderator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,099
    Thanks
    169
    Thanked 779 Times in 725 Posts
    Blog Entries
    5

    Default Re: Always Catch Exceptions

    Thanks for the post Tj. I moved this to the Programming Tutorials section where it will hopefully get more visibility.

Similar Threads

  1. how do i try/catch this?
    By safra in forum Exceptions
    Replies: 6
    Last Post: October 29th, 2011, 11:14 AM
  2. Try, catch? array help
    By alkamenes in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 14th, 2011, 11:17 PM
  3. [SOLVED] While try catch loop
    By Duaber in forum What's Wrong With My Code?
    Replies: 10
    Last Post: June 23rd, 2011, 02:14 PM
  4. catch all
    By silverspoon34 in forum Exceptions
    Replies: 1
    Last Post: November 29th, 2009, 01:18 PM
  5. try/catch
    By rsala004 in forum Exceptions
    Replies: 5
    Last Post: July 19th, 2009, 03:20 PM