Programming Tips - Java: make a exception look nicer before showing it to users

Date: 2019jun20 Update: 2025jun27 Language: Java Q. Java: make a exception look nicer before showing it to users A. Here is a function for that.
import java.lang.System; class Demo { // ex.toString() gives "java.io.FileNotFoundException <msg>" // while this gives "FileNotFound <msg>" private static String prettyException(final Exception ex) { String name = ex.getClass().getSimpleName(); name = name.replace("Exception", ""); return name + " " + ex.getMessage(); } public static void main(String[] args) { try { // Cause a divide by zero exception final int i = 0; final int j = 42 / i; } catch(Exception ex) { System.out.println(" ugly exception=" + ex.toString()); String pretty = prettyException(ex); System.out.println("pretty exception=" + pretty); } } }
Outputs:
ugly exception=java.lang.ArithmeticException: / by zero pretty exception=Arithmetic / by zero