Aravindh an
Aravindh an

Reputation: 369

can't java unchecked exceptions be handled using try/catch block?

In a tutorial I found that Unchecked Exception can't be handled by your code i.e. we can't use try/catch block and the examples are exceptions like ArrayIndexOutOfBoundsException, NullPointerException. But these exceptions can be handled using try/catch block. I think i am not clear about the concept !!

Also i think throw keyword can be used only with try/catch block.can throw Keyword be used with UncheckedException?

Upvotes: 34

Views: 69792

Answers (8)

Learner
Learner

Reputation: 547

Yes you can handle the unchecked exception but not compulsory. Actually it depends on application developer. Below is the possible reason where i think required to handle even unchecked exception.

  • If your application is large where many developers are calling each other API. It is better to handle the unchecked exception otherwise at the end your program will crash which stop the other functionality. So even the simple NullPointerException can stop your program working.

  • Imagine you have one scheduler which processing the user data and which is in million size and for the bad data you only want to print the log not to stop working for other good data. In that case if you have not handle the exception one bad data can stop your program

Upvotes: 0

Abinash Sing
Abinash Sing

Reputation: 1

yes we can handle Runtime Exception, plz check below code

public class Demo {
  static void m1() {
    int a[]=new int [5];
    try {
    a[12]=2;
    }catch(Exception e) {

    }
  }

  public static void main(String[] args) {
    m1();
   try {
    String s=null;

    System.out.println(s.length());
   }catch(Exception e) {

   }
    System.out.println("hello world");
  }
}

Upvotes: -3

Michael Borgwardt
Michael Borgwardt

Reputation: 346476

The only difference between checked and unchecked exceptions is that checked ones have to be either caught or declared in the method signature using throws, whereas with unchecked ones this is optional.

Unchecked Exception can't be handled by your code i.e. we can't use try/catch block

Sure we can - but we don't have to.

Also i think throw keyword can be used only with try/catch block.can throw Keyword be used with Unchecked Exception?

Note that there are two keywords:

  • throw explicitly throws an exception object you created. throw new NullPointerException(); works perfectly fine, though explicitly creating that particular exception is uncommon and most would consider it bad style.
  • throws declares that a method may throw that exception. With unchecked exceptions this is optional, but can be useful to document the fact (again, one would normally not declared throws NullPointerException because that is pretty much a given).

Upvotes: 46

Puce
Puce

Reputation: 38152

In addition to Guillaume:

  • unchecked exceptions are usually programming errors, which should not happen at all if implemented correctly (index out of bound, null pointer, class cast,...) and therefore the caller/ user usually cannot do anything about them.
  • checked exceptions are thrown because it was outside of the control of the programmer (network not availabe, filesystem not available, concurrent modifications such as duplicated primary key,...)
  • errors are usually thrown by the JVM and the application usually has to stop (out of memory, stack overflow,...)

Upvotes: 4

Guillaume
Guillaume

Reputation: 22822

They can be handled, but you don't have to. If you don't handle them, they will propagate and climb up the calling methods stack, until one of them catches it. If none does, the program will crash.

Usually, the bottom line is that if a client can reasonably be expected to recover from an exception, then it should be a checked exception. If a client cannot do anything to recover from the exception, then it's ok to have it as an unchecked exception.

Also, checked exceptions are useful to document an API that you expect to be used by 3rd-parties. When they know your method can throw a specific exception, they will code accordingly and handle the case. If you only use unchecked exceptions, all bets are off.

A common pattern (some people don't like it, but in some cases it's ok when you know what you're doing) is to wrap thrown checked exceptions into unchecked ones.

try {
   ... code that can throw CheckedException ...
} catch (CheckedException oopsSomethingBadHappened) {
    throw new RuntimeException("Something bad happened!", oopsSomethingBadHappened);
}

Upvotes: 5

Óscar López
Óscar López

Reputation: 236112

All the unchecked exceptions can be treated in the same way as the checked ones - if you want, you can let them pass by declaring that the method throws them:

public void m() throws RuntimeException {}

Or you can catch them:

public void m() {
    try {
        // some code
    } catch (RuntimeException re) {
        // do something
    }
}

It should be noticed, the class RuntimeException acts as a catch-all for the unchecked exceptions (since all the unchecked exceptions extend from it), much in the same way that the Exception class is the catch-all for checked exceptions.

As has been mentioned before, the only real difference is that for checked exceptions you have to handle them (by letting them pass or catching them) and the compiler will make sure of it - on the other hand, the handling of unchecked exceptions is optional.

It all boils down to the expected usage of each exception type - you're supposed do be able to recover from checked exceptions (or at least do something about them, when they occur), whilst for unchecked exceptions, there might not be a reasonable way to recover from them. This of course, is a bit subjective.

Upvotes: 11

Chris
Chris

Reputation: 23179

An easy way to think about the difference is to think the checking refers to the compile. If an exception is a checked exception, the compiler will check that your code either throws the exception or handles it in a try/catch block at compile-time. For unchecked exceptions, the compiler won't do such a check. You can handle checked/unchecked exceptions the same way (with try/catch/throws), the difference just lies in the checks the compiler performs. This post has a decent example.

Upvotes: 4

tobiasbayer
tobiasbayer

Reputation: 10389

Yes, you can throw unchecked exceptions with throw. And yes, you can catch unchecked exceptions in a catch block.

Upvotes: 0

Related Questions