Java try block:
Java try block is used to enclose the code that might throw an exception. It must be used within the method.
If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.
Java catch block:
Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, a good approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch block with a single try block.
How to use a try-catch clause
try { // block of code to monitor for errors // the code you think can raise an exception } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 }
Points to remember :
Consider the below code and guess the output for it:
class InterviewBit { public static void main (String[] args) { // array of size 4. int[] arr = new int[10]; try { int i = arr[14]; System.out.print("A" + " "); } catch(ArrayIndexOutOfBoundsException ex) { System.out.print("B"+ " "); } System.out.println("C"); } }