Explain try and catch exception in java?
Why use exceptions instead of return values?
1. Forces error checking
2. Cleans up your code through separating the normal case from the exceptional case. (The code isn't littered along with a lot of if-else blocks checking return values.)
3. Low overhead for non-exceptional case
Traditional programming languages set flags or return bad values such as -1 to denotes problems. Programmers frequent don't check these values.
Java throws Exception objects to denotes a problem. These cannot be ignored.
try-catch
try-catch
public class HelloThere {
public static void main(String[] args) {
try {
System.out.println("Hello " + args[0]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Hello Whoever you are.");
}
}