public class exception4{


public static void method(){

try{
exception4.method2();
throw new Exception("method throw");
}
catch(Exception e)
{
System.out.println("method Exception caught"+ e);
//throw e;
}


}

public static void method2(){

try{
throw new Exception("method2 throw");
}
catch(Exception e)
{
System.out.println("method2 Exception caught"+ e);

e.printStackTrace();
[B]//throw e;  
[/B] [U]if include this statement it show error [/U]
}

}

public static void main(String args[]){

System.out.println("exception program");

try{

exception4.method();

}
catch(Exception e)
{
System.out.println("main Exception caught"+ e);
}

}


}

Edited 5 Years Ago by __avd: Added [code] tags.

same problem in the case of user defined exception also..

class MException extends Exception{

public MException(String str)
{

super(str);


} 



} 







public class exception4{


public static void method(){

try{
exception4.method2();
throw new MException("method throw");
}
catch(MException e)
{
System.out.println("method Exception caught"+ e);
throw e;
}


}

public static void method2(){

try{
throw new MException("method2 throw");
}
catch(MException e)
{
System.out.println("method2 Exception caught"+ e);

e.printStackTrace();
//throw e;

}

}

public static void main(String args[]){

System.out.println("exception program");

try{

exception4.method();

}
/*catch(MException e)
{
System.out.println("main Exception caught"+ e);
}*/

finally{
}

}


}

exception4.java:33: unreported exception MException; must be caught or declared
to be thrown
throw e;
^
1 error

Edited 5 Years Ago by __avd: Added [code] tags.

First example:

public class exception4 {

	public static void method() throws Exception { // 4. Added "throws Exception" here.

		try {
			exception4.method2();
			throw new Exception("method throw");
		} catch (Exception e) {
			System.out.println("method Exception caught" + e);
			throw e; // 3. Uncommented this line.
		}
	}

	public static void method2() throws Exception { // 2. Added "throws Exception" here.
		try {
			throw new Exception("method2 throw");
		} catch (Exception e) {
			System.out.println("method2 Exception caught" + e);

			e.printStackTrace();
			throw e; // 1. Uncommented this line.
		}
	}

	public static void main(String args[]) {
		System.out.println("exception program");
		try {
			exception4.method();
		} catch (Exception e) {
			System.out.println("main Exception caught" + e);
		}
	}
}

Second example:

class MException extends Exception {
	private static final long serialVersionUID = 1L;  // 5. to fix this warning: "The serializable class MException does not declare a static final serialVersionUID field of type long"
	public MException(String str) {
		super(str);
	}
}

public class exception4 {

	public static void method() throws MException { // 4.
		try {
			exception4.method2();
			throw new MException("method throw");
		} catch (MException e) {
			System.out.println("method Exception caught" + e);
			throw e; // 3.
		}
	}

	public static void method2() throws MException { // 2.
		try {
			throw new MException("method2 throw");
		} catch (MException e) {
			System.out.println("method2 Exception caught" + e);

			e.printStackTrace();
			throw e; // 1.
		}
	}

	public static void main(String args[]) {
		System.out.println("exception program");
		try {
			exception4.method();
		} catch (MException e) {
			System.out.println("main Exception caught" + e);
		} finally {
		}
	}
}

If you find that you don't like to have to deal with so many "try-catch" blocks and "throws" clauses, then consider extending RuntimeException .

(Now that the code works, here is something else to consider: It's generally a bad idea to both "handle" an exception (by logging or printing it, for example) and also rethrow it. "Handle it or throw it. Don't do both." is a good general rule.)

If you find that you don't like to have to deal with so many "try-catch" blocks and "throws" clauses, then consider extending RuntimeException .
(Now that the code works, here is something else to consider: It's generally a bad idea to both "handle" an exception (by logging or printing it, for example) and also rethrow it. "Handle it or throw it. Don't do both." is a good general rule.)

thank u sir i got it...

  1. but without final long serialVersionUID (variable)..its working fine ..what is the purpose of that variable...

  2. can we use fillinstacktrace()method to update exception...or default it will update..

  3. another in exception creation

Code:

class MException extends Exception{


public MException(String str)
{
super(str);
}
} 


super (str)-----> it will send the string to base class constructor(Exception class)--->in the exception class it will send base class constructor(Throwable class)


in lang packge,exception class
public Exception(String message) {
super(message);
}



in lang packge,throwable class
public Throwable(String message) {
fillInStackTrace();//shall we use this method manually..
detailMessage = message;
}

but my question is how to assign the string("exception parameter or error msg") to exception object...

if we print the object it will print the error message....

Edited 3 Years Ago by pyTony: fixed formatting

The Java compiler warning message, "The serializable class MException does not declare a static final serialVersionUID field of type long" is a WARNING message, not a "stop the presses" error. So you can ignore it if you want.

If you fail to provide a serialVersionUID value, the compiler will generate one for you automatically. This is really only a problem if you "save a copy" of the exception message in some persistent store and then run an updated version of your program after changing the implementation of that exception. In that case, you will have problems restoring the saved object to memory.

Since it is highly unlikely that you will attempt to do the above, you can feel free to ignore the warning message.

Some warnings, however, indicate serious problems in programs. They can often point out real bugs. So I make a habit of "fixing" all warnings. Good clean code should compile with no warning messages at all. You have to define the serialVersionUID variable to get rid of that warning message. It doesn't really matter what value you give it. It's a version number, so starting from one does make a fair amount of sense.

Calling super in a constructor does actually call the corresponding superclass constructor and execute its code. So fillInStackTrace(); does get called for you; you don't have to call it again.

Regarding your last question...

but my question is how to assign the string("exception parameter or error msg") to exception object...

if we print the object it will print the error message....

Hmmm... It works fine in both of your example programs above.

Try doing this in method2: throw new MException("exception parameter or error msg"); I get this result:

exception program
method2 Exception caughtMException: exception parameter or error msg
method Exception caughtMException: exception parameter or error msg
main Exception caughtMException: exception parameter or error msg
MException: exception parameter or error msg
	at exception4.method2(exception4.java:22)
	at exception4.method(exception4.java:12)
	at exception4.main(exception4.java:34)

Perhaps you are changing the throw in the first method. That throw never executes because the call to method2 throws an exception, causing the calling method to skip down to the catch block.

Regarding your last question...

Hmmm... It works fine in both of your example programs above.

Try doing this in method2: throw new MException("exception parameter or error msg"); I get this result:

exception program
method2 Exception caughtMException: exception parameter or error msg
method Exception caughtMException: exception parameter or error msg
main Exception caughtMException: exception parameter or error msg
MException: exception parameter or error msg
	at exception4.method2(exception4.java:22)
	at exception4.method(exception4.java:12)
	at exception4.main(exception4.java:34)

Perhaps you are changing the throw in the first method. That throw never executes because the call to method2 throws an exception, causing the calling method to skip down to the catch block.

k sir my question is.. how the exception object assign string parameter(error msg)....how the object print error message..(y am asking again is same thing follows on thread also but in different manner)

in exception - error message or error name

in thread- thread name

in exception creation "class MException extends Exception{

public MException(String str)
{
super(str);[B]------->this cons method how to assign string parameter to object...[/B]
} 
} "



in lang packge,exception class
public Exception(String message) {
super(message);
}


in lang packge,throwable class
public Throwable(String message) {
fillInStackTrace();//shall we use this method manually..
detailMessage = message;//fiinally it string message stopped here
}

2.what is the difference between system.out.println and system.err.println
both are print same...

Edited 5 Years Ago by sathya88: n/a

k sir my question is.. how the exception object assign string parameter(error msg)....how the object print error message..

If your question is "How did the exception print the error message I passed to it when I created it, along with a stack trace?", then the answer is that one of your catch blocks does this: e.printStackTrace();

2.what is the difference between system.out.println and system.err.println
both are print same...

Yes, by default both print to the console.

See: http://download.oracle.com/javase/6/docs/api/java/lang/System.html

Under "Field Summary", you'll see the definitions of "err", "in" and "out".

In Unix, and other POSIX-compatible systems (such as Microsoft Windows) every program that runs is given, by default "standard input", "standard output" and "standard error" input and output files. These map to Java's "System.in", "System.out" and "System.err". By default, standard input / System.in is keyboard input, and both "outputs" display on the screen/console.

Something that can be very confusing is the lines written to System.out and System.err are buffered; they are not printed right away. So they may appear on your screen in a different order than they happened. All the lines written to System.out will be in the correct order. But the relative positions of "out" and "err" lines may be unpredictable.

So...
You often see exception messages and stack traces "interleaved" with "System.out" messages that you printed. In other words, they display on the screen "in the wrong order."

This is normal. It is not a bug in your program or in Java. That's just the way things work.

If your question is "How did the exception print the error message I passed to it when I created it, along with a stack trace?", then the answer is that one of your catch blocks does this: e.printStackTrace();

actually when ever exception throwned it will stored in a stack...
if view all exception throwned in the program we use printstacktrace method...

my question is...

in catch block we print a object ...how it will print a error message...

how assign error message to that object...

Edited 5 Years Ago by sathya88: n/a

Attachments
/*
 * %W% %E%
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.lang;

/**
 * The class <code>Exception</code> and its subclasses are a form of 
 * <code>Throwable</code> that indicates conditions that a reasonable 
 * application might want to catch.
 *
 * @author  Frank Yellin
 * @version %I%, %G%
 * @see     java.lang.Error
 * @since   JDK1.0
 */
public class Exception extends Throwable {
    static final long serialVersionUID = -3387516993124229948L;

    /**
     * Constructs a new exception with <code>null</code> as its detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     */
    public Exception() {
	super();
    }

    /**
     * Constructs a new exception with the specified detail message.  The
     * cause is not initialized, and may subsequently be initialized by
     * a call to {@link #initCause}.
     *
     * @param   message   the detail message. The detail message is saved for 
     *          later retrieval by the {@link #getMessage()} method.
     */
    public Exception(String message) {
	super(message);
    }

    /**
     * Constructs a new exception with the specified detail message and
     * cause.  <p>Note that the detail message associated with
     * <code>cause</code> is <i>not</i> automatically incorporated in
     * this exception's detail message.
     *
     * @param  message the detail message (which is saved for later retrieval
     *         by the {@link #getMessage()} method).
     * @param  cause the cause (which is saved for later retrieval by the
     *         {@link #getCause()} method).  (A <tt>null</tt> value is
     *         permitted, and indicates that the cause is nonexistent or
     *         unknown.)
     * @since  1.4
     */
    public Exception(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Constructs a new exception with the specified cause and a detail
     * message of <tt>(cause==null ? null : cause.toString())</tt> (which
     * typically contains the class and detail message of <tt>cause</tt>).
     * This constructor is useful for exceptions that are little more than
     * wrappers for other throwables (for example, {@link
     * java.security.PrivilegedActionException}).
     *
     * @param  cause the cause (which is saved for later retrieval by the
     *         {@link #getCause()} method).  (A <tt>null</tt> value is
     *         permitted, and indicates that the cause is nonexistent or
     *         unknown.)
     * @since  1.4
     */
    public Exception(Throwable cause) {
        super(cause);
    }
}
/*
 * %W% %E%
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.lang;
import  java.io.*;

/**
 * The <code>Throwable</code> class is the superclass of all errors and
 * exceptions in the Java language. Only objects that are instances of this
 * class (or one of its subclasses) are thrown by the Java Virtual Machine or
 * can be thrown by the Java <code>throw</code> statement. Similarly, only
 * this class or one of its subclasses can be the argument type in a
 * <code>catch</code> clause.
 *
 * <p>Instances of two subclasses, {@link java.lang.Error} and
 * {@link java.lang.Exception}, are conventionally used to indicate
 * that exceptional situations have occurred. Typically, these instances
 * are freshly created in the context of the exceptional situation so
 * as to include relevant information (such as stack trace data).
 *
 * <p>A throwable contains a snapshot of the execution stack of its thread at
 * the time it was created. It can also contain a message string that gives
 * more information about the error. Finally, it can contain a <i>cause</i>:
 * another throwable that caused this throwable to get thrown.  The cause
 * facility is new in release 1.4.  It is also known as the <i>chained
 * exception</i> facility, as the cause can, itself, have a cause, and so on,
 * leading to a "chain" of exceptions, each caused by another.
 *
 * <p>One reason that a throwable may have a cause is that the class that
 * throws it is built atop a lower layered abstraction, and an operation on
 * the upper layer fails due to a failure in the lower layer.  It would be bad
 * design to let the throwable thrown by the lower layer propagate outward, as
 * it is generally unrelated to the abstraction provided by the upper layer.
 * Further, doing so would tie the API of the upper layer to the details of
 * its implementation, assuming the lower layer's exception was a checked
 * exception.  Throwing a "wrapped exception" (i.e., an exception containing a
 * cause) allows the upper layer to communicate the details of the failure to
 * its caller without incurring either of these shortcomings.  It preserves
 * the flexibility to change the implementation of the upper layer without
 * changing its API (in particular, the set of exceptions thrown by its
 * methods).
 *
 * <p>A second reason that a throwable may have a cause is that the method
 * that throws it must conform to a general-purpose interface that does not
 * permit the method to throw the cause directly.  For example, suppose
 * a persistent collection conforms to the {@link java.util.Collection
 * Collection} interface, and that its persistence is implemented atop
 * <tt>java.io</tt>.  Suppose the internals of the <tt>add</tt> method
 * can throw an {@link java.io.IOException IOException}.  The implementation
 * can communicate the details of the <tt>IOException</tt> to its caller
 * while conforming to the <tt>Collection</tt> interface by wrapping the
 * <tt>IOException</tt> in an appropriate unchecked exception.  (The
 * specification for the persistent collection should indicate that it is
 * capable of throwing such exceptions.)
 *
 * <p>A cause can be associated with a throwable in two ways: via a
 * constructor that takes the cause as an argument, or via the
 * {@link #initCause(Throwable)} method.  New throwable classes that
 * wish to allow causes to be associated with them should provide constructors
 * that take a cause and delegate (perhaps indirectly) to one of the
 * <tt>Throwable</tt> constructors that takes a cause.  For example:
 * <pre>
 *     try {
 *         lowLevelOp();
 *     } catch (LowLevelException le) {
 *         throw new HighLevelException(le);  // Chaining-aware constructor
 *     }
 * </pre>
 * Because the <tt>initCause</tt> method is public, it allows a cause to be
 * associated with any throwable, even a "legacy throwable" whose
 * implementation predates the addition of the exception chaining mechanism to
 * <tt>Throwable</tt>. For example:
 * <pre>
 *     try {
 *         lowLevelOp();
 *     } catch (LowLevelException le) {
 *         throw (HighLevelException)
                 new HighLevelException().initCause(le);  // Legacy constructor
 *     }
 * </pre>
 *
 * <p>Prior to release 1.4, there were many throwables that had their own
 * non-standard exception chaining mechanisms (
 * {@link ExceptionInInitializerError}, {@link ClassNotFoundException},
 * {@link java.lang.reflect.UndeclaredThrowableException},
 * {@link java.lang.reflect.InvocationTargetException},
 * {@link java.io.WriteAbortedException},
 * {@link java.security.PrivilegedActionException},
 * {@link java.awt.print.PrinterIOException},
 * {@link java.rmi.RemoteException} and
 * {@link javax.naming.NamingException}).
 * All of these throwables have been retrofitted to
 * use the standard exception chaining mechanism, while continuing to
 * implement their "legacy" chaining mechanisms for compatibility.
 *
 * <p>Further, as of release 1.4, many general purpose <tt>Throwable</tt>
 * classes (for example {@link Exception}, {@link RuntimeException},
 * {@link Error}) have been retrofitted with constructors that take
 * a cause.  This was not strictly necessary, due to the existence of the
 * <tt>initCause</tt> method, but it is more convenient and expressive to
 * delegate to a constructor that takes a cause.
 *
 * <p>By convention, class <code>Throwable</code> and its subclasses have two
 * constructors, one that takes no arguments and one that takes a
 * <code>String</code> argument that can be used to produce a detail message.
 * Further, those subclasses that might likely have a cause associated with
 * them should have two more constructors, one that takes a
 * <code>Throwable</code> (the cause), and one that takes a
 * <code>String</code> (the detail message) and a <code>Throwable</code> (the
 * cause).
 *
 * <p>Also introduced in release 1.4 is the {@link #getStackTrace()} method,
 * which allows programmatic access to the stack trace information that was
 * previously available only in text form, via the various forms of the
 * {@link #printStackTrace()} method.  This information has been added to the
 * <i>serialized representation</i> of this class so <tt>getStackTrace</tt>
 * and <tt>printStackTrace</tt> will operate properly on a throwable that
 * was obtained by deserialization.
 *
 * @author  unascribed
 * @author  Josh Bloch (Added exception chaining and programmatic access to
 *          stack trace in 1.4.)
 * @version %I%, %G%
 * @since JDK1.0
 */
public class Throwable implements Serializable {
    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -3042686055658047285L;

    /**
     * Native code saves some indication of the stack backtrace in this slot.
     */
    private transient Object backtrace;

    /**
     * Specific details about the Throwable.  For example, for
     * <tt>FileNotFoundException</tt>, this contains the name of
     * the file that could not be found.
     *
     * @serial
     */
    private String detailMessage;

    /**
     * The throwable that caused this throwable to get thrown, or null if this
     * throwable was not caused by another throwable, or if the causative
     * throwable is unknown.  If this field is equal to this throwable itself,
     * it indicates that the cause of this throwable has not yet been
     * initialized.
     *
     * @serial
     * @since 1.4
     */
    private Throwable cause = this;

    /**
     * The stack trace, as returned by {@link #getStackTrace()}.
     *
     * @serial
     * @since 1.4
     */
    private StackTraceElement[] stackTrace;
    /*
     * This field is lazily initialized on first use or serialization and
     * nulled out when fillInStackTrace is called.
     */

    /**
     * Constructs a new throwable with <code>null</code> as its detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     *
     * <p>The {@link #fillInStackTrace()} method is called to initialize
     * the stack trace data in the newly created throwable.
     */
    public Throwable() {
        fillInStackTrace();
    }

    /**
     * Constructs a new throwable with the specified detail message.  The
     * cause is not initialized, and may subsequently be initialized by
     * a call to {@link #initCause}.
     *
     * <p>The {@link #fillInStackTrace()} method is called to initialize
     * the stack trace data in the newly created throwable.
     *
     * @param   message   the detail message. The detail message is saved for
     *          later retrieval by the {@link #getMessage()} method.
     */
    public Throwable(String message) {
        fillInStackTrace();
        detailMessage = message;
    }

    /**
     * Constructs a new throwable with the specified detail message and
     * cause.  <p>Note that the detail message associated with
     * <code>cause</code> is <i>not</i> automatically incorporated in
     * this throwable's detail message.
     *
     * <p>The {@link #fillInStackTrace()} method is called to initialize
     * the stack trace data in the newly created throwable.
     *
     * @param  message the detail message (which is saved for later retrieval
     *         by the {@link #getMessage()} method).
     * @param  cause the cause (which is saved for later retrieval by the
     *         {@link #getCause()} method).  (A <tt>null</tt> value is
     *         permitted, and indicates that the cause is nonexistent or
     *         unknown.)
     * @since  1.4
     */
    public Throwable(String message, Throwable cause) {
        fillInStackTrace();
        detailMessage = message;
        this.cause = cause;
    }

    /**
     * Constructs a new throwable with the specified cause and a detail
     * message of <tt>(cause==null ? null : cause.toString())</tt> (which
     * typically contains the class and detail message of <tt>cause</tt>).
     * This constructor is useful for throwables that are little more than
     * wrappers for other throwables (for

actually when ever exception throwned it will stored in a stack...
if view all exception throwned in the program we use printstacktrace method...

Not quite: The system does not store a stack or history of all exceptions thrown in the program. Each exception has a class (some class that extends Throwable or one of its children), a String message, and the "stack trace" array. The "stack trace" array contains a representation of the stack at the time the exception was created. In a sense, it is a very limited history of the methods that called the method that created the exception.

(The initCause/getCause methods can be seen as a stack of exceptions. But it is used only when one exception causes another or if you want to nest exceptions. It is not a history of all exceptions thrown.)

my question is...

in catch block we print a object ...how it will print a error message...

how assign error message to that object...

If you want to get the error message from an exception, call the getMessage() method:

/**
     * Returns the detail message string of this throwable.
     *
     * @return  the detail message string of this <tt>Throwable</tt> instance
     *          (which may be <tt>null</tt>).
     */
    public String getMessage() {
        return detailMessage;
    }

Your program does print the error message ("MException: method2 throw") three times, by using the .toString() method of the exception. If you want to get the String "method2 throw" from the exception, then call the getMessage() method.

This question has already been answered. Start a new discussion instead.