Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

What is the difference between checked and unchecked exceptions in java? Why do we throw using 'throws' exception instead of catching them?

share|improve this question
1  
Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. Also see How to Ask –  gnat Oct 28 at 10:00
1  
already asked on so: stackoverflow.com/questions/6115896/… –  Zavior Oct 28 at 10:50
1  
The answer to this question can be found on Stack Overflow - stackoverflow.com/questions/6115896/… –  ChrisF Oct 28 at 11:37

put on hold as off-topic by Kilian Foth, Philipp, ChrisF Oct 28 at 11:37

  • This question does not appear to be about software development within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer

A checked exception requires that you add a throws declaration to the method signature, or you add a try catch block around it.

public void checked() throws IOException {
  throw new IOException(); // compiles just fine
}

public void checked() {
  try {
    throw new IOException();
  } catch (IOException e) {
    // ...
  }
}

This will not work:

public void checkedWithoutThrows() {
  throw new IOException(); // will not compile
}

An unchecked exception does not need this.

public void unchecked() {
  throw new RuntimeException();
}

And, just for completeness, the way to determine unchecked from checked exceptions is that unchecked exceptions all descend from RuntimeException at some point or another.

share|improve this answer
 
Thanks KepaniHaole, It is very helpful for me. Your examples are very easy to understand. Can you please tell me about the difference between 'throw' and 'throws'?? –  Arnav Kumar Oct 28 at 11:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.