Results 1 to 3 of 3
  1. #1
    javaplus is offline Member
    Join Date
    Nov 2007
    Posts
    97
    Rep Power
    0

    Default Better way to handle exceptions

    I need your advice on this one. I wrote my own Exception class which as follows.

    Java Code:
    public class ParserException extends Exception {
    	
    	public ExtractorException(String msg){
    		super(msg);
            }
    }
    It works perfectly fine. I have another option which is as follows:

    Java Code:
    public class ParserException extends Exception {
    	private String expMsg;
    
    	public ExtractorException(String msg){
    		this.expMsg = msg;
            }
    
            public String getExpMsg() {
    		return expMsg;
    	}
    
    	public void setExpMsg(String expMsg) {
    		this.expMsg = expMsg;
    	}
    }
    Please tell me which is the preferred way?

    thanks in advance.

  2. #2
    roots's Avatar
    roots is offline Moderator
    Join Date
    Jan 2008
    Location
    Dallas
    Posts
    293
    Rep Power
    7

    Default

    First one is better than second one.

    You are defining your own message accessing methods even though there is already similar method in Exception Class. Normally exception messages are available during the creation of the exception message.
    Further to that it requires the code that is catching this exception to be tightly coupled with this code meaning it needs to know how to get the message. In situation where this exception is caught by default handler such as JVM which called main method wont be able to show the message.

    Second option has it's benefit as well but you should use it only when required for example you need to set the message down the exception chain.

    Java Code:
    catch(ParserException ex){
      String rootMessage = ex.getExpMsg();
      ex.setExpMsg(rootMessage + "SOME EXTRA DATA");
      throw ex ;
    }
    I wish other will contribute as well in this topic ..
    dont worry newbie, we got you covered.

  3. #3
    javaplus is offline Member
    Join Date
    Nov 2007
    Posts
    97
    Rep Power
    0

Similar Threads

  1. How to handle socket Exception
    By mayank0512 in forum Networking
    Replies: 14
    Last Post: 12-22-2010, 12:31 AM
  2. [SOLVED] Handle own exception
    By stevemcc in forum New To Java
    Replies: 3
    Last Post: 04-10-2008, 05:55 AM
  3. handle wrong input int/null
    By Camden in forum New To Java
    Replies: 1
    Last Post: 12-16-2007, 10:37 PM
  4. how to handle exceptions
    By paty in forum Advanced Java
    Replies: 2
    Last Post: 08-05-2007, 05:17 AM
  5. Replies: 1
    Last Post: 06-07-2007, 06:29 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •