try catch mandatory

gudii9 used Ask the Experts™
checked exception

public class ThrowEx {

      public static void main(String[] args) {
            throw new Exception("file not there");
            catch(Exception e){



why i ned to have try catch for above example.

If i skip i am getting compilation error

Exception could be Run time(unchecked which does not need explicit try catch like indexoutofbound, arthematic) , unchecked(which needs explicit try catch like IOException)
as well right?

please advise
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
With just the code you provided, the program compiles fine without a try catch block for me. The compiler requires exceptions being handled when they are checked exceptions like all child classes of the Exception class except for the RuntimeException as you already stated. If you have a class that throws a checked exception, you must declare this in the functions head using the throws keyword.

But I wonder why you throw an exception in the try block. This means the program always throws that exception.


how unchecked exception and run time exceptions are different?
as per above diagram both seems same?
Checked Exceptions are checked by the compiler (hence the name) and thus a java program won't compile if such an exception is not handled.
Unchecked exceptions will only be verified at runtime and thus there is not really a difference between unchecked and RuntimeException. The latter is however a subclass of Exception and thus Throwable, meaning that unchecked is a more general term, since for example exceptions under Error are unchecked too.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial