Results 1 to 11 of 11
  1. #1
    anandjain1984 is offline Member
    Join Date
    Dec 2009
    Posts
    3
    Rep Power
    0

    Default whether to use try/catch block or throws keyword

    if we are writing a java code, then how to decide whether to handle the exception using try/catch block or handle the exception using throws keyword

  2. #2
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

    Default

    It depends. If you can handle the exception locally it's a try catch, if you can't or don't want to do that you use throws. There is no general rule that you can apply, it's a matter of experience when to use what.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  3. #3
    Krooger is offline Member
    Join Date
    Nov 2008
    Posts
    43
    Rep Power
    0

    Default

    Personaly I try to use try/catch as much as possible. I find it makes using that code from other parts of the program much easier than having to always catch its thorwn exception. Then only use throws if there is a reason I cant use try/catch.

  4. #4
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default

    Catch the Exception if you can do something about it. One option is to catch the Exception, log it, and then throw it from the catch block. You can also wrap the Exception in a RuntimeException and throw the RTE, which eliminates the need to declare the original exception. This makes sense for an Exception you never expect to see, but that can't be ignored.

    Obviously, all the above assumes that you are actually doing the right thing with the Exception. If you can't handle it (appropirately), then declare it.

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    And my tuppence...:)

    Never throw Exception, or RuntimeException. Always throw something meaningful. If you're throwing a RuntimeException then document it! Do not treat it as a way to avoid doing some work. I am not a fan of wrapping normal exceptions as Runtime ones for his very reason...exceptions have a tendency to get hidden.

    In a similar way, never catch Exception...always catch something more specific.

    And finally, many people get concerned (as above) about throwing lots of different exceptions. Your project, and each bit of your project, should have its own collection of exceptions (a nice tree of them) that get passed up between the layers. These should represent the business logic failures that have occurred, but will have the original exception wrapped in them (don't want to lose info after all).

  6. #6
    renamed is offline Member
    Join Date
    Dec 2009
    Location
    Rio de Janeiro
    Posts
    38
    Rep Power
    0

    Default

    I once read that we should never throw a "NullPointerException" because it is mostly used by JVM.

    I only catch exceptions if I need to log it or if I'm developing a class that is directly communicating with the user, like a "Insert user screen", for example.
    Please don't laugh at my English... I'm trying my best! :)

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    Throwing an NPE is valid if the method it's thrown from specifies that one or more of its parameters cannot be null. As with all Rules Of Thumb (ROT) there will always be exceptions...:) Pun intended...

  8. #8
    renamed is offline Member
    Join Date
    Dec 2009
    Location
    Rio de Janeiro
    Posts
    38
    Rep Power
    0

    Default

    I know Tolls... I'm not saying it is wrong.

    The author said that this kind of exception is used by JVM several times and use it may be confusing when trying to reach an error.

    He said an IllegalArgumentException could be thrown by your methods if you get a null parameter.

    It's his point of view. I think if you do something like the below is enough.

    Java Code:
    public void x (Object a){
       if (a == null){
            throw new NullPointerException("Parameter 'a' in method 'x' cannot be null");
       }
    }
    Please don't laugh at my English... I'm trying my best! :)

  9. #9
    FON
    FON is offline Senior Member
    Join Date
    Dec 2009
    Location
    Belgrade, Serbia
    Posts
    368
    Rep Power
    5

    Default

    Always think about real life scenarios and the way your app must
    end some use case.

    Rarely will you just catch some exception, just log it and do nothing with it.

    In most cases, when you catch it (you try to catch most specific one not just generic Exception) you must continue your app logic and end negative scenario.

    Here is very useful to simply wrap that specific exception in your own created one,
    and after catching specific one throw your own MyException further through methods,
    all way to first caller object which has logic for finishing negative scenario.

    Here is sample code for yours general exception.
    You simply create your own exceptions, just use EXTENDS on this class:


    Java Code:
    public class MyGeneralException extends Exception{
    
    	//error message 
    	private String realMessage = null;
    
    	//real exception.
    	private Exception realException = null;
    
    	
    	
    	/*3 constructors so you can create exception based on just message, just exception or both*/
    	
    	public MyGeneralException(String realMessage){
    		this(realMessage,null);
    	}
    
    
    	public MyGeneralException(String realMessage, Exception realException) {
    		this.realMessage = realMessage;
    		this.realException = realException;
    	}
    
    	public MyGeneralException(Exception realException) {
    		this(realException.getMessage(),realException);
    	}
    
    
    	
    	
    	/*getters and setters */
    	public String getRealMessage() {
    		return realMessage;
    	}
    
    
    	public void setRealMessage(String realMessage) {
    		this.realMessage = realMessage;
    	}
    
    
    	public Exception getRealException() {
    		return realException;
    	}
    
    	public void setRealException(Exception realException) {
    		this.realException = realException;
    	}
    }

    regards :)

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    Quote Originally Posted by renamed View Post
    He said an IllegalArgumentException could be thrown by your methods if you get a null parameter.
    Actually, good point...that would make more sense.
    I sit corrected!
    :)

  11. #11
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default

    I agree with the overall sentiments, but "never" is a long time. Exception handling should be carried out using appropriate strategies. Catch, log, and go on is appropriate in some instances, but it is over used and conceals problems. My point is to *allow* exceptions to continue up the chain if you don't know what to do about them. Wrapping an exception with a RuntimeException doesn't conceal it if the exception occurs; I said to do it only if the exception is extremely unusual.

    As far as catching Exception, I often catch Throwable, which also catches RuntimeExceptions. I do this because I have a clear strategy to execute if a problem occurs; most of the time, the strategy does not depend on the particular exception.

Similar Threads

  1. Try/catch block
    By swati.jyoti in forum New To Java
    Replies: 5
    Last Post: 07-02-2009, 02:32 PM
  2. Question reg try/catch block
    By nn12 in forum New To Java
    Replies: 1
    Last Post: 09-16-2008, 05:56 PM
  3. System.exit() in catch block.
    By new_2_java in forum Advanced Java
    Replies: 8
    Last Post: 06-24-2008, 03:45 PM
  4. Try Catch block issues
    By kewlgeye in forum New To Java
    Replies: 11
    Last Post: 04-29-2008, 07:10 AM
  5. try...catch block
    By javaplus in forum New To Java
    Replies: 3
    Last Post: 11-06-2007, 07:53 PM

Posting Permissions

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