Exception message is not showing

import java.util.*;
class WrongException extends Exception{

    public WrongException(String s){

        super(s);
    }
}
public class UserDefinedException2{

    public static void main(String s[]){

        int a,b;
        a=b=0;
        Scanner ob=new Scanner(System.in);
        System.out.print("Enter your age = ");
        a=ob.nextInt();
        try
        {
            if(a<=0)
            throw new WrongException("age cannot be zero or nagetive");
            System.out.print("age = "+a);
        }
        catch(WrongException e){

            System.out.print("wrong");
        }
    }
 }

throw new WrongException("age cannot be zero or nagetive") this message is not showing why??
and this message is showing System.out.print("wrong") please help me

Recommended Answers

All 8 Replies

The message is not showing because you have not written any code to show it.
In your catch block, instead of printing "wrong" you should print the exception.

either that, or, remove the try and catch block alltogether, and add a throws WrongException to your method signature.

I am by far a fan of having a main method throwing Exceptions, but it 'll give the same result as any other method that doesn't use exception handling, but delegates the responsability to the calling method

there are two messages line 21 and line 26 how can i arrange it i mean how to display message of line 21.

Line 21 you create an Exception object with that message. There's no printing there.
Line 26 you just print "wrong".
You can change line 26 to print the actual exception, ie
System.out.println(e);

its mean we can show messages with two ways first in throwing exception and second after catch clause but i want to print message of line 21 only

No. Throwing an exception doesn't show any message.
An Exception is an object that contains information about a problem. When you find a problem you create an Exception object to describe it.
You then "throw" that exception object so somebody else can "catch" it and deal with the problem. It's the person who catches it who decides what to print (or show in a GUI dialog box, or log to an error log).

e.printStackTrace() in the catch block

write System.out.println(e.getMessage();

commented: adds nothing, syntax is wrong -3
commented: I feel sick when I see System.out.println in any code! For god sake use Logger -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.