Java - Custom ExceptionsYou want to create a custom exception that includes an error code along with the message. Which is the best way to implement this?AUse Error class and add static error code variableBExtend Exception and add an int field with constructor to set code and messageCExtend RuntimeException and override toString() without fieldsDCreate a class with only static methods returning error messagesCheck Answer
Step-by-Step SolutionSolution:Step 1: Understand the need for custom data in exceptionTo include an error code, the exception class must have a field and constructor to set it.Step 2: Choose the correct base class and designExtending Exception (checked) and adding an int field with constructor is the proper way to carry extra info.Final Answer:Extend Exception and add an int field with constructor to set code and message -> Option BQuick Check:Custom exception with extra data = add fields and constructor [OK]Quick Trick: Add fields and constructor to custom exception for extra info [OK]Common Mistakes:Using Error class for application exceptionsNot adding fields to hold extra dataUsing static variables instead of instance fields
Master "Custom Exceptions" in Java9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More Java Quizzes Abstraction - Partial abstraction - Quiz 12easy Constructors - This keyword usage - Quiz 6medium Constructors - Default constructor - Quiz 13medium Constructors - This keyword usage - Quiz 12easy Custom Exceptions - Exception propagation - Quiz 13medium Encapsulation - Encapsulation best practices - Quiz 4medium Exception Handling - Multiple catch blocks - Quiz 2easy Exception Handling - Multiple catch blocks - Quiz 13medium Inheritance - Constructor chaining - Quiz 11easy Interfaces - Default methods - Quiz 14medium