Thursday, July 6, 2017

Exception - Can not Get any Simpler than This

Exception handling by custom exceptions is as easy as extending the Exception class. 


java.lang.Object
     java.lang.Throwable
         java.lang.Exception

Look at the API documentation to learn what you can do like what constructors are available and what methods you will have access to by extending this class.

Method Summary

  The most useful constructor for this purpose is the constructor that takes a string as its parameter since it will allow you to set a custom message for your custom exception class.  To get this message later, you will use the getMessage() method that is inherited from Throwable ( as seen above ).

To practice this concept, implement the following code and make modifications as you see it fit.  Create more exceptions and change the messages until it makes sense and you feel comfortable with this easy and useful object oriented concept.  Have fun!




public class HelloDriver{
    public static void main(String args[])throws MyException{  //the other is passed to JVM
         try{
             Hello msg=new Hello("Hello"," World");
             System.out.println(msg.getHello());         
         }
         catch(MyException2 e){                                        //one of the exceptions are handled here
             System.out.println("Zoltan: "+e.getMessage());
         }
    }
}

==============================================================

public class Hello extends World{
private String hello;

//because the parent constuctor with string parameter was called, the exception must be handled
//coming from the parent's constructor and also from this constructor
public Hello(String h, String w)throws MyException2,MyException{
    super(w);
    if(h.equals("He11o"))
       hello=h;
    else
        throw new MyException2();
}

public String getHello(){
    return hello+getWorld();
}
}

===============================================================

public class World{
private String world;

public World(String msg)throws MyException{   //pas the exception out of the constuctor
    if(msg.equals(" World"))
       world=msg;
    else
       throw new MyException();     //create exception if condition is met
}

public String getWorld(){
    return world;
}
}

===============================================================

public class MyException extends Exception
{
public MyException(){
    super("Your message was cool!!!");   //call the parent class Exception constructor with string parameter
}
}

================================================================

public class MyException2 extends Exception
{
public MyException2(){
    super("Your message was the coolest!!!"); //call the parent class Exception constructor with string parameter
}
}