+ 1

Java, confused with Exception(String message)

hi, I am very confused with " exception(String message)". Why when the above exception is triggered, the "message" will be printed out?? I did not see a function that literally says" System.out.print(message)"? Don't we need to add this function ourselves?? Or did I miss it in Throwable or Exception?? I saw some code, for example: public class LabyrinthException extends Exception { /** * Creates a new exception and defines the message. * * @param description the description of the problem. */ LabyrinthException(String description) { super(description); } /** * Creates a new exception caused by another exception and defines the message. * * @param description the description of the problem. * @param cause the cause for this exception. */ LabyrinthException(String description, Throwable cause) { super(description, cause); } } //and: public final class NoGameFieldException extends LabyrinthException { private static final String MESSAGE_INVALID_GAME_FIELD = "The position (%d,%d) is not a valid game field."; /** * @param pawnPosX the horizontal position accessed. * @param pawnPosY the vertical position accessed. */ public NoGameFieldException(int pawnPosX, int pawnPosY) { super(MESSAGE_INVALID_GAME_FIELD.formatted(pawnPosX, pawnPosY)); } } //and: private void validatePosition(int posX, int posY) throws LabyrinthException { if (0 > posX || 0 > posY || horizontalSize <= posX || verticalSize <= posY) { throw new NoGameFieldException(posX, posY); } } So it seems that if the function validatePosition triggers the "NoGameFieldException", which is inherited from "LabyrinthException ", then the error message ""The position (%d,%d) is not a valid game field." will be printed out. My question is why?? I go through java manual, it does not explain why this error message, that is , the thi

6th Nov 2022, 1:29 PM
siviaseason
siviaseason - avatar
1 Réponse
+ 1
validatePosition() method is checked, so there is catch() and catch can print LabyrinthException object try { new ExceptionTest() .validatePosition( 100,100); } catch (LabyrinthException ex) { System.out.println( ex); // here } println() calls Exception.toString() method inherited from Throwable public String toString() { String s = getClass().getName(); String message = getLocalizedMessage(); return (message != null) ? (s + ": " + message) : s; } Throwable has our message from constructor of NoGameFieldException(...) where is super(msg)
6th Nov 2022, 8:09 PM
zemiak