Logger throwing() method in Java with Examples
Last Updated :
28 Mar, 2019
throwing(String sourceClass, String sourceMethod, Throwable thrown) method is used to Log throwing an exception.In many scenario method is closed by throwing an exception then this is a very helpful method to log that a method is terminating by throwing an exception. The logging is done using the FINER level logging. If the level of the logger is set to log FINER level logging then the given arguments are stored in a log record with a message THROW which is forwarded to all registered output handlers.
Syntax:
public void throwing(String sourceClass,
String sourceMethod,
Throwable thrown)
Parameters: This method accepts three parameters:
- sourceClass is the name of the class that issued the logging request,
- sourceMethod is the name of the method and
- result is The Throwable that is being thrown.
Return value: This method returns nothing.
Below programs illustrate throwing(String sourceClass, String sourceMethod, Object result) method:
Program 1:
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class GFG {
public static void main(String[] args)
throws SecurityException, IOException
{
Logger logger
= Logger.getLogger(
GFG. class .getName());
FileHandler handler
= new FileHandler( "logs.txt" );
handler.setFormatter( new SimpleFormatter());
logger.addHandler(handler);
logger.setLevel(Level.FINER);
logger.setLevel(Level.FINER);
logger.throwing(GFG. class .getName(),
GFG. class .getMethods()[ 0 ].getName(),
new IOException());
}
}
|
The output printed on log.txt is shown below.
Output:
Program 2:
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class GFG {
static Logger logger
= Logger.getLogger(
GFG. class .getName());
public static void main(String[] args)
throws SecurityException, IOException
{
FileHandler handler
= new FileHandler( "logs.txt" );
logger.addHandler(handler);
logger.setLevel(Level.FINER);
logger.setLevel(Level.FINER);
logger.throwing(String. class .getName(),
String. class .getMethods()[ 0 ].getName(),
new ArithmeticException());
}
}
|
The output printed on log.txt is shown below.
Output:
Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#throwing(java.lang.String, java.lang.String, java.lang.Throwable)
Share your thoughts in the comments
Please Login to comment...