Results 1 to 4 of 4
  1. #1
    esolve is offline Member
    Join Date
    Mar 2015
    Posts
    56
    Rep Power
    0

    Default why do we need "throws"?

    if there are exceptions, even if we don't use throws,
    try-catch can still catch the exceptions.

    so why do we need "throws"?

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: why do we need "throws"?

    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,716
    Rep Power
    18

    Default Re: why do we need "throws"?

    Quote Originally Posted by esolve View Post
    if there are exceptions, even if we don't use throws,
    try-catch can still catch the exceptions.

    so why do we need "throws"?
    Do read the page Jim linked to. try/catch is effective for the exceptions that occur in other code that our method is calling, but how do we tell callers of our code that we have detected an exception with something they are trying to do? For that we throw an exception so that their try/catch can take care of it.

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: why do we need "throws"?

    Also (and pbrockway2 may have implied this in his response), it allows the method to pass on the responsibility of catching checked exceptions which the method would normally be required to catch. If you specify throws on the method signature, you do not need to enclose the associated checked exception in a try/catch block.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. "Error cannot find symbol" "throws BadLocationException"
    By Daniel Silvester in forum New To Java
    Replies: 8
    Last Post: 07-02-2013, 01:53 AM
  2. Replies: 0
    Last Post: 12-07-2012, 08:29 AM
  3. Replies: 2
    Last Post: 02-22-2012, 07:22 PM
  4. Simple Swing throws Exception in thread "AWT-EventQueue-0"
    By sultanofswing in forum AWT / Swing
    Replies: 3
    Last Post: 10-29-2010, 09:20 PM
  5. Reserved word "throws"
    By Lil_Aziz1 in forum New To Java
    Replies: 5
    Last Post: 01-02-2010, 02:12 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
  •