-1

I have a bit of confusion in the following snippet.

try {

public static void showMyName(String str) throws IOException
  {
      if(str.equals("What is your Name?"))
            throw new IOException;
  }

 }catch(IOException e)
   {
      System.out.println ("Exception occurs , catch block called")
   }

Now, my question is what is difference between throws IOException && throw new IOException

Why don't we require to use catch , finally block for throws IOException ?

How does throws is handle the exception. ?

anacron
  • 6,443
  • 2
  • 26
  • 31
Mitul Maheshwari
  • 2,647
  • 4
  • 24
  • 38

5 Answers5

2

When an Exception is generated, there are two ways to deal with it.

  1. Handle the Exception - this uses catch block
  2. Declare the Exception - this uses throws block

So, dealing with an already generated exception is done by catch or throws.

On the other hand, throw is used while an Exception is "generated".

Typically, the throw keyword is used when you're instantiating an Exception object or while cascading an already generated exception to the caller.

For example,

public void doSomething(String name) throws SomeException { // Exception declared
    if( name == null ){ // cause of the exception
        throw new SomeException(); // actual NEW exception object instantiated and thrown
    }
    // Do something here
    .
    .
    .
}

In the calling method,

public static void main(String[] args) throws SomeException{ // Need to declare exception because you're "throwing" it from inside this method.
    try { // try doing some thing that may possibly fail
        doSomething(name);
    } catch (SomeException e){
        throw e;// throw the exception object generated in doSomething()
    }
}

Alternately, you can "handle" the exception in the catch block:

public static void main(String[] args) { // No need to declare exception
    try { // try doing some thing that may possibly fail
        doSomething(name);
    } catch (SomeException e){
        System.out.println("Exception occurred " + e.getMessage()); // Handle the exception by notifying the user.
    }
}

Hope this helps.

Addendum - Exception Handling glossary

  • try - used for invoking code that can potentially cause exceptions or with resources such as Files/Streams/Network/Database connections.
  • catch - used immediately after a try block to "handle" or "throw" exceptions. Optional if finally is used.
  • finally - used immediately after a try or catch block. Optional. Used for executing code that "must" be executed. Code within a finally block always gets executed - even if the try or catch has a return statement.
  • throw - used to "push" or "cascade" exceptions through the calling methods. Always used inside a method.
  • throws - used to "declare" that a method will be throwing an exception if something goes wrong. Always used as part of method signature.

Addional Reading

Here's an elaborate article to help you understand the try-catch-finally semantics in java.

Update

To answer your other question,

Why don't we require to use catch , finally block for throws IOException ?

Think of catch and throws as mutually exclusive constructs. (This is not always true, but for your understanding, it's good to start with this thought.)

You declare a method that it throws IOException. This piece of code is written at a point where you declare the method. And, syntactically, you cannot place a method declaration inside a try block.

How does throws is handle the exception. ?

Like I mentioned before, catch and finally are used during exception handling. throws is just used to cascade the exception back to the caller.

anacron
  • 6,443
  • 2
  • 26
  • 31
1

throw new IOException means that you encountered some error condition and decided to break the flow of the program by throwing an exception.

If that exception is a checked exception (i.e. not Error or RuntimeException), you must either catch that exception in a catch block, or declare in the method's signature that the method is expected to throw that exception (or a super-class of that exception). That's what the throws IOException means.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

You are pretty much right on. Except for one thing I'll mention in a bit.

throws is as much a part of the method API as the name and the parameters. Clients know if they call that method, they need to handle that exception--by simply throwing it also or by catching it and handling it (which may in fact entail the throwing of another exception wrapping the original). throws is addressed at compile time.

throw is the actual act of letting the runtime know something bad happened--that the exceptional condition we were worried about has in fact taken place. So it needs to be dealt with at runtime.

But you weren't quite right when you said, "Throws in method signature should always appear if there exist a throw statement in the method." That is often true but not always. I could also call another method that throws an exception within my method, and if I don't catch it, my method needs to throw it. In that case, there is no explicit throw of the same exception by me.

The final point is that you only need to declare an exception in throws when the exception is a checked exception--meaning it is from the other side of the Exception class hierarchy from RuntimeException. Common checked exceptions are IOException and SQLException. Checked exceptions must be listed in the throws part of the method signature if you don't handle them yourself. Anything subclassing RuntimeException--like NoSuchElementException in your example and also the hated NullPointerException--is an unchecked exception and doesn't have to be caught or thrown or anything.

Typically, you use checked exceptions for recoverable problems (where the client knows what can happen and can gracefully handle the problem and move on) and unchecked exceptions for catastrophic problems (like can't connect to the database).

If you can get past all the AOP stuff, this is a great discussion of how you use checked and unchecked exceptions effectively.

Santhi Bharath
  • 2,818
  • 3
  • 28
  • 42
1

The first biggest difference is throw can throw exception like you throw stone in river, and throws state that this method have chances to throw exception but may not also... and thats why throws dont need try catch because it state already that it gona throw some kind of exception.

Vijay Patel
  • 163
  • 2
  • 14
1

throws keyword means that this method will throw any Exception that will have to be handled in a higher level.

public static void showMyName(String str) throws IOException

If another method call this method, it has to catch this exception or throw it one more time (by typing throws in its signature).

Catch the exception or keep throwing it, depends on your business logic.

Héctor
  • 24,444
  • 35
  • 132
  • 243