try catch mandatory

gudii9
gudii9 used Ask the Experts™
on
checked exception



public class ThrowEx {

      public static void main(String[] args) {
            
            try{
            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


https://www.google.com/search?q=java+exception+checked&safe=active&rlz=1C1GGRV_enUS765US765&source=lnms&tbm=isch&sa=X&ved=0ahUKEwi_7qLdjLjaAhWDylMKHfzxDigQ_AUICigB&biw=1280&bih=615#imgdii=dKyeLgDJI-TIrM:&imgrc=Xm7qPed58fGj2M:

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
Comment
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.

Author

Commented:
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