JAVA : EXCEPTION : HIERARCHY
why cant we use new Exception(myMsg) instead of new MyException(myMsg) .....?
We can handle different exception separately like
catch(MyException e) { //do some operation ..}
catch(Exception e) { //do some other operaton...}
Custom Exception Class:
Example1: With out super(str2)
Example2: With super(str)
O/P
why cant we use new Exception(myMsg) instead of new MyException(myMsg) .....?
We can handle different exception separately like
catch(MyException e) { //do some operation ..}
catch(Exception e) { //do some other operaton...}
Custom Exception Class:
Example1: With out super(str2)
class MyException extends Exception{ String str1; MyException(String str2) { str1=str2; //Note: not calling super(str2) } public String toString(){ return ("MyException Occurred: "+str1) ; } } class Example1{ public static void main(String args[]){ //Note: throws is not require, bez JVM will take care try{ System.out.println("Starting of try block"); // I'm throwing the custom exception using throw throw new MyException("This is My error Message"); } catch(MyException exp){ System.out.println("Catch Block") ; System.out.println(exp) ; //prints .toString() } } }O/P
Starting of try block Catch Block MyException Occurred: This is My error Message
Example2: With super(str)
class InvalidProductException extends Exception { public InvalidProductException(String s) { // Call constructor of parent Exception super(s); //Using super } } public class Example1 { void productCheck(int weight) throws InvalidProductException{ //Note : throws is require bez its our custom method and it is checked exception if(weight<100){ throw new InvalidProductException("Product Invalid"); } } public static void main(String args[]) { Example1 obj = new Example1(); try { obj.productCheck(60); } catch (InvalidProductException ex) { System.out.println("Caught the exception"); System.out.println(ex.getMessage()); } } }
O/P
Caught the exception Product Invalid
No comments:
Post a Comment