PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 4, 2022

[FIXED] How to stop printing the StackTrace of exceptions in the console

 August 04, 2022     exception, java     No comments   

Issue

If an exception is thrown without catching it, the default behaviour is to print the exception stack trace in the console. How to do to change this behaviour for example to write something else in the console or do some tasks wihtout catching those excpetions.

The goal is to stop writing the stackTrace for all the Exceptions and do any other task , for example write "No output here !" if an Exception is thrown .

public class Tester {
    public static void main(String[] args) {
        throw new RuntimeException("my message");
    }
}

Output :

Exception in thread "main" java.lang.RuntimeException: my message
    at src.Tester.main(Tester.java:17)

Excpected Output:

No output here !

Solution

From the Java documentaiton here : A thread can take full control of how it responds to uncaught exceptions by having its uncaught exception handler explicitly set. So you can simply call the setUncaughtExceptionHandler method of the current thread and create your own UncaughtExceptionHandler instance, passing this instance to the method as argument exactly like that :

import java.lang.Thread.UncaughtExceptionHandler;

public class Tester {
    public static void main(String[] args) {

        Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                // write here the new behaviour and it will be applied for all the uncaughted Exceptions
                System.out.println("No output here !");
            }
        });

        throw new RuntimeException("my message");
    }
}

Output :

No output here !


Answered By - Oussama ZAGHDOUD
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing