71

What is the difference between try-catch and throw clause. When to use these?

Please let me know .

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
user393043
  • 807
  • 1
  • 9
  • 9
  • possible duplicate of [Throws or try-catch](http://stackoverflow.com/questions/3203297/throws-or-try-catch) – Pascal Thivent Sep 25 '10 at 18:23
  • @Pascal Thivent: I think we've established the OP's google-foo and general clue-fullness are extremely limited :) – Dave Sep 25 '10 at 18:39
  • 1
    @Dave Yeah, which is why I think low quality questions like this one should get closed, especially given that I'm pretty sure the answer is already there. TBH, I just don't know if this is the best dupe. I'll let the OP find a better one :) – Pascal Thivent Sep 25 '10 at 19:01
  • @Pascal Thivent:I agree that it should be closed, I just see it as an opportunity to be snarky :) However, @Colin Hebert did actually answer the question, so... – Dave Sep 25 '10 at 19:25
  • @Dave Hehe :) Regarding duplicates, It doesn't matter if people do answer them (I'd actually expect high rep users to not do so when questions are obvious dupes), they remain duplicates and they dilute the good stuff that you can find on SO. That's why duplicates are bad, they should just get closed, IMO. – Pascal Thivent Sep 25 '10 at 19:57
  • @Pascal Thivent: Let me be clear I agree with you; I just want to get my useless answer voted up :) – Dave Sep 25 '10 at 20:22
  • @Pascal Thivent, I agree with you on the fact that duplicates should be closed and that everybody should search before asking,but I must say,I rarely saw questions where you can't find at least one duplicate on SO,and even less where you can't find the answer by googling for 15 mins (and most of those questions remain unanswered).In this case, which questions are worth to be asked and which ones deserve to be answered?Again, I agree with the fact that duplicates are polluting the good answers on SO, but if no-one (at least, among the askers) looks at them, does it worth it to chase duplicates? – Colin Hebert Sep 25 '10 at 22:00
  • @Colin IMO, answering obvious dupes is not good: firstly, it lowers the quality of the content and secondly, it doesn't educate people. So to sum up, it doesn't encourages the right behavior at all and I'll thus never agree on anything promoting this practice and consider hunting dupes as highly valuable. Sadly, the system doesn't offer any incentive for finding duplicates and many people favor the easy rep they get by answering obvious dupes over closing questions. But I expect more from regular users. That's just my personal opinion though. – Pascal Thivent Sep 26 '10 at 01:45
  • Try http://tutorials.jenkov.com/java-exception-handling/index.html and http://download.oracle.com/javase/tutorial/essential/exceptions/ and http://www.javabeginner.com/learn-java/understanding-java-exceptions – President James K. Polk Sep 25 '10 at 18:09

8 Answers8

99
  • The try block will execute a sensitive code which can throw exceptions
  • The catch block will be used whenever an exception (of the type caught) is thrown in the try block
  • The finally block is called in every case after the try/catch blocks. Even if the exception isn't caught or if your previous blocks break the execution flow.
  • The throw keyword will allow you to throw an exception (which will break the execution flow and can be caught in a catch block).
  • The throws keyword in the method prototype is used to specify that your method might throw exceptions of the specified type. It's useful when you have checked exception (exception that you have to handle) that you don't want to catch in your current method.

Resources :


On another note, you should really accept some answers. If anyone encounter the same problems as you and find your questions, he/she will be happy to directly see the right answer to the question.

Colin Hebert
  • 91,525
  • 15
  • 160
  • 151
  • You didn't address the *throws* clause. I need you to do this so that when he accepts my answer, I can refer him to yours :) – Dave Sep 25 '10 at 18:24
41

If you execute the following example, you will know the difference between a Throw and a Catch block.

In general terms:

The catch block will handle the Exception

throws will pass the error to his caller.

In the following example, the error occurs in the throwsMethod() but it is handled in the catchMethod().

public class CatchThrow {

private static void throwsMethod() throws NumberFormatException {
    String  intNumber = "5A";

    Integer.parseInt(intNumber);
}

private static void catchMethod() {
    try {

        throwsMethod();

    } catch (NumberFormatException e) {
        System.out.println("Convertion Error");
    }

}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    catchMethod();
}

}
user1864519
  • 433
  • 4
  • 6
  • For example, if you change the "private static void throwsMethod() throws NumberFormatException" as "private static void throwsMethod() throws IndexOutOfBoundsException", it produces the same result. – Ken Vors Aug 23 '15 at 14:24
  • this example is so clear that I can easily understand the difference between try-catch and throw. Thank you~ – KY Lu Dec 26 '21 at 20:08
6

Try/catch and throw clause are for different purposes. So they are not alternative to each other but they are complementary.

  1. If you have throw some checked exception in your code, it should be inside some try/catch in codes calling hierarchy.

  2. Conversely, you need try/catch block only if there is some throw clause inside the code (your code or the API call) that throws checked exception.

Sometimes, you may want to throw exception if particular condition occurred which you want to handle in calling code block and in some cases handle some exception catch block and throw a same or different exception again to handle in calling block.

Mahesh
  • 611
  • 9
  • 16
6

All these keywords try, catch and throw are related to the exception handling concept in java. An exception is an event that occurs during the execution of programs. Exception disrupts the normal flow of an application. Exception handling is a mechanism used to handle the exception so that the normal flow of application can be maintained. Try-catch block is used to handle the exception. In a try block, we write the code which may throw an exception and in catch block we write code to handle that exception. Throw keyword is used to explicitly throw an exception. Generally, throw keyword is used to throw user defined exceptions.

For more detail visit Java tutorial for beginners.

Ellen gomez
  • 61
  • 1
  • 2
1

Others have already given thorough answers, but if you're looking for even more information, the Oracle Java tutorials are always a good resource. Here's the Java tutorial for Exceptions, which covers all of your questions in great detail; https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html

BNeumann
  • 76
  • 4
0

try block contains set of statements where an exception can occur.

catch block will be used to used to handle the exception that occur with in try block. A try block is always followed by a catch block and we can have multiple catch blocks.

finally block is executed after catch block. We basically use it to put some common code when there are multiple catch blocks. Even if there is an exception or not finally block gets executed.

throw keyword will allow you to throw an exception and it is used to transfer control from try block to catch block.

throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.

// Java program to demonstrate working of throws, throw, try, catch and finally.

 public class MyExample { 
      
        static void myMethod() throws IllegalAccessException 
        { 
            System.out.println("Inside myMethod()."); 
            throw new IllegalAccessException("demo"); 
        } 
      
        // This is a caller function  
        public static void main(String args[]) 
        { 
            try { 
                myMethod(); 
            } 
            catch (IllegalAccessException e) { 
                System.out.println("exception caught in main method."); 
            }
            finally(){
                System.out.println("I am in final block.");
            } 
        } 
    } 

Output:

Inside myMethod().
exception caught in main method.
I am in final block.
datta ambareesh
  • 141
  • 1
  • 8
-1

In my limited experience with the following details.throws is a declaration that declares multiple exceptions that may occur but do not necessarily occur, throw is an action that can throw only one exception, typically a non-runtime exception, try catch is a block that catches exceptions that can be handled when an exception occurs in a method,this exception can be thrown.An exception can be understood as a responsibility that should be taken care of by the behavior that caused the exception, rather than by its upper callers. I hope my answer will help you

-2

try - Add sensitive code catch - to handle exception finally - always executed whether exception caught or not. Associated with try -catch. Used to close the resource which we opened in try block throw - To handover our created exception to JVM manually. Used to throw customized exception throws - To delegate the responsibility of exception handling to caller method or main method.