Try and Catch in Java
Exception
When your code can throw an exception (error on run time), you can wrap that code in try and catch block.
Example: ArrayIndexOutOfBoundsException
Code
public class TryAndCatch { public static void main( String[] args ){ String str = "Hello"; char[] charArr = str.toCharArray(); try { char lastChar = charArr[charArr.length]; System.out.println(lastChar); } catch(ArrayIndexOutOfBoundsException e) { e.printStackTrace(); //System.out.println("Index number out of scope"); } } }
Output
java.lang.ArrayIndexOutOfBoundsException: 5
at TryAndCatch.main(TryAndCatch.java:8)
Multiple Catch Blocks
public class TryAndCatch { public static void main( String[] args ){ String str = "Hello"; char[] charArr = str.toCharArray(); try { char lastChar = charArr[charArr.length - 1]; System.out.println(lastChar); String subStr = str.substring(8); } catch(ArrayIndexOutOfBoundsException e) { e.printStackTrace(); //System.out.println("Index number out of scope"); } catch(StringIndexOutOfBoundsException e) { System.out.println("String index out of bound!"); } } }
Output
String index out of bound!
Custom Exception
public class TryAndCatch { public static void main( String[] args ){ String str = "Hello"; char[] charArr = str.toCharArray(); try { if (charArr.length < 10) { throw (new Exception("My custom exception")); //this will look for catch block } char lastChar = charArr[charArr.length - 1]; System.out.println(lastChar); String subStr = str.substring(8); } catch(ArrayIndexOutOfBoundsException e) { e.printStackTrace(); //System.out.println("Index number out of scope"); } catch(StringIndexOutOfBoundsException e) { System.out.println("String index out of bound!"); } catch(Exception e) { System.out.println(e.getMessage()); } } }
Output
My custom exception
Notes
- A try block must be followed by at least 1 catch block.
- e is just a name given to exception and it can be reused.
- If your code generates an exception then it will stop to that point itself and not execute further. So, even if you have 2 exceptions, only first will be displayed.