try{ System.out.println(string.length()); } catch(NullPointerException e){ System.out.println("Please pass a valid string !"); }If enclosed code may lead to different exceptions in different situations, one can use multiple suspected catch blocks after the try block.
try { System.out.println(string.length()); } catch (NullPointerException e) { System.out.println("Please pass a valid string !"); } catch (Exception e1) { System.out.println("Please pass a valid string !"); }
package com.tb.demo; class Main { void printSize(String string) { try { System.out.println(string.length()); try { System.out.println(string.substring(4)); } catch (NullPointerException e) { System.out.println("Please pass a valid string !"); } } catch (NullPointerException e) { System.out.println("Please pass a valid string !"); } } }A try catch block combination may be declared inside another catch block as shown below.
package com.tb.demo; class Main { void printSize(String string) { try { System.out.println(string.length()); } catch (NullPointerException e) { try { System.out.println(string.substring(4)); } catch (NullPointerException e1) { System.out.println("Please pass a valid string !"); } } } }In nested try catch, the inner try block uses its own catch block as well as catch block of the outer try, if required.
package com.tb.demo; class Main { void printSize(String string) { try { System.out.println(string.length()); } catch (NullPointerException e) { System.out.println(e.toString()); } } public static void main(String args[]) { Main main = new Main(); main.printSize(null); } }Output : java.lang.NullPointerException
2014-2017 © Techburps. ALL Rights Reserved. Disclaimer Contact Us