Bird
0
0

You want to create a custom exception that includes an error code along with the message. Which is the best way to implement this?

hard📝 Application Q8 of 15
Java - Custom Exceptions
You 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 variable
BExtend Exception and add an int field with constructor to set code and message
CExtend RuntimeException and override toString() without fields
DCreate a class with only static methods returning error messages
Step-by-Step Solution
Solution:
  1. Step 1: Understand the need for custom data in exception

    To include an error code, the exception class must have a field and constructor to set it.
  2. Step 2: Choose the correct base class and design

    Extending Exception (checked) and adding an int field with constructor is the proper way to carry extra info.
  3. Final Answer:

    Extend Exception and add an int field with constructor to set code and message -> Option B
  4. Quick 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 exceptions
  • Not adding fields to hold extra data
  • Using static variables instead of instance fields

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes