Mrs B February 2016

is the value of java class object same as class name?

Hi i am a beginner in java programming and was having trouble understanding what a value of an object would be. I was debugging the following program and while looking under the variables tab in eclipse I saw variable name as ex and value as Exception. I did not understand if the instance of a class has a value same as class name. can somebody please help.

public void abc(int i)throws Exception{
    i++;
    throw new Exception("Exception");
}
public static void main(String [] args){
    try{
        Test t = new Test();
        t.abc(5);
    }catch(Exception ex){
        System.out.println(ex.toString());
    }
}

Answers


yanis February 2016

In your case the instance of the class Exception has value "Exception". You have set it in abc method. If you change the value in the constructor of the Exception class like:

throw new Exception("Some value");

You will have that "Some value" as a result.


Zbynek Vyskovsky - kvr000 February 2016

The value of exception is whatever you pass to its constructor:

throw new Exception("Exception");

As you pass string "Exception", you see the same as ex value later.

In general the better way to print exception is to use its printStackTrace method which gives much more details why it happened:

 ex.printStackTrace();

Post Status

Asked in February 2016
Viewed 3,848 times
Voted 5
Answered 2 times

Search




Leave an answer