Home » Java programming language

Java Throwable setStackTrace() Method with Example

Throwable Class setStackTrace() method: Here, we are going to learn about the setStackTrace() method of Throwable Class with its syntax and example.
Submitted by Preeti Jain, on January 06, 2020

Throwable Class setStackTrace() method

  • setStackTrace() Method is available in java.lang package.
  • setStackTrace() Method is used to sets stack trace elements that will be retrieved by using getStackTrace() method.
  • setStackTrace() Method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • setStackTrace() Method may throw an exception at the time of setting stack trace elements.
    NullPointerException – This exception may throw when the given argument is null or when any of its existing elements of the stack trace is null.

Syntax:

    public void setStackTrace(StackTraceElement[] st_tr);

Parameter(s):

  • StackTraceElement[] st_tr – represents an array of "StackTraceElement".

Return value:

The return type of the method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of void setStackTrace(StackTraceElement[] st_tr)
// method of Throwable 

public class SetStackTrace {
    public static void main(String args[]) {
        try {
            stackTraceMethod();
        } catch (Throwable ex) {

            // By using getStackTrace() method is to get the
            // stack trace element
            StackTraceElement[] st_tr = ex.getStackTrace();
            System.err.println("st_tr[0].toString()" + st_tr[0].toString());
        }
    }

    public static void stackTraceMethod() throws Throwable {
        int li_nu = 7;
        // instantiate a new exception called 
        // Throwable
        Throwable th = new Throwable("Raise New Exception");
        StackTraceElement[] st_tr = new StackTraceElement[] {
            new StackTraceElement("cl_na", "me_na", "fu_na", li_nu)
        };

        // By using setStackTrace() method is to set
        // the elements in stack
        th.setStackTrace(st_tr);
        throw th;
    }
}

Output

st_tr[0].toString()cl_na.me_na(fu_na:7)





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.