0% found this document useful (0 votes)
25 views2 pages

Creating Custom Exceptions in Java

This document discusses creating custom exceptions in Java. It explains that custom exceptions can be created by subclassing the Exception class. An example is provided that creates a MyException class that extends Exception. The example overrides the toString() method and throws a MyException if a parameter is greater than 10. The main method catches the MyException and prints the error message. The lab tasks ask the student to create an exception class for validating a cinema customer's age and another exception class for validating a money deposit amount.

Uploaded by

ghazi members
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views2 pages

Creating Custom Exceptions in Java

This document discusses creating custom exceptions in Java. It explains that custom exceptions can be created by subclassing the Exception class. An example is provided that creates a MyException class that extends Exception. The example overrides the toString() method and throws a MyException if a parameter is greater than 10. The main method catches the MyException and prints the error message. The lab tasks ask the student to create an exception class for validating a cinema customer's age and another exception class for validating a money deposit amount.

Uploaded by

ghazi members
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Own-Exception in Java Lab#14

LAB # 14

CREATING YOUR OWN-EXCEPTION

OBJECTIVE:
To study to create your own exception.

THEORY:

14.1 CREATING YOUR OWN EXCEPTION


SUBCLASSES
Although Java’s built-in exceptions handle most common errors, you will
probably want to create your own exception types to handle situations specific
to your applications.
This is quite easy to do: just define a subclass of Exception (which is, of
course, a subclass of Throwable). The Exception class does not define any
methods of its own. It does, of course, Inherit those methods provided by
Throwable. Thus, all exceptions, including those that you create, have the
methods defined by Throwable available to them. You may also wish to
override one or more of these methods in exception classes that you create.
The following example declares a new subclass of Exception and then uses
that subclass to signal an error condition in a method. It overrides the
toString( ) method,
Allowing the description of the exception to be displayed using println( ).

// This program creates a custom exception type.


class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
[Link]("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
[Link]("Normal exit");
}

Object Oriented Programming - OOPs 1


Own-Exception in Java Lab#14

public static void main(String args[]) {


try {
compute(1);
compute(20);
} catch (MyException e) {
[Link]("Caught " + e);
}
}}

OUTPUT:

LAB TASK

1. Add an exception class that calls a method to throw an exception to


invigilate customer’s age in the cinema hall. When the user enters age
less than 18 so an exception should be created displaying not eligibility
message in the output.
2. Drive two Classes. One is of exception class and another is of using
the exception class, prompt to deposit the money ranging from 1000 to
50,000 and display “money has been deposit.” else generate an “error.”
by calling the exception in both the cases.
(Hint: try-catch)

Object Oriented Programming - OOPs 2

Common questions

Powered by AI

Try-catch blocks in Java are used to handle exceptions gracefully. When implementing a money deposit feature with a range restriction, you create a custom exception class, for instance, DepositRangeException, extending Exception. In the deposit method, check if the deposit amount is outside the specified range (1000 to 50,000). If it is, throw the DepositRangeException. The try block would contain the code that attempts the deposit, and the catch block would handle DepositRangeException by informing the user of the error, such as displaying "error". This use of try-catch allows for clean separation of normal logic and error handling .

To implement a custom exception for age restrictions in a Java application, you create an exception class, for instance, AgeRestrictionException, extending Exception. In a method where the age is evaluated, use a condition to check if the age is below 18. If it is, throw an instance of AgeRestrictionException with a message indicating that the patron is not eligible. In the example architecture, your method for checking age would look something like: if (age < 18) throw new AgeRestrictionException("Patron must be 18 or older.").

Custom exceptions enhance code readability and maintainability by encapsulating error conditions specific to business logic. They allow developers to handle exceptions with semantic clarity, using descriptive names to indicate errors. For instance, an AgeRestrictionException clearly signals an issue with age verification in an application, directly embedding the rule as a class. This leads to cleaner code by reducing complex conditional checks scattered across application logic. Consequently, updates or changes to business rules affecting age restrictions can be easily managed by modifying this single class, instead of pervasive code changes .

In Java, creating custom exceptions involves inheritance, where a new exception class is formed by extending the existing Exception class, itself a subclass of Throwable. This inheritance relationship ensures that the new custom exception possesses all methods and behaviors of Throwable, such as tracking stack traces or providing exception messages. An example can be seen where MyException extends Exception, and inherits from it without needing to redefine existing logic, focusing only on adding specific functionality like additional data fields or method overrides .

Overriding the toString() method in a custom Java exception class provides a meaningful description of the exception instance, which can be useful for logging or debugging. In the provided example, the override of toString() in the MyException class formats the output to include the error details: "MyException[detail]", where 'detail' is an integer passed during exception creation. This makes the exception's message more informative when printed with println(), aiding in understanding the error context .

To create a custom exception in Java, you define a class that extends the Exception class, which, in turn, extends Throwable. This allows you to signal specific error conditions that are unique to your application. For instance, if your program requires handling a condition not covered by built-in exceptions, a custom exception provides a clear and structured way to manage that scenario. By overriding methods, such as toString(), you can define how the exception is represented or logged, as shown in the example where MyException is created with a detail integer to indicate the error's specifics .

The provided example illustrates error signaling via custom exceptions, as seen where compute throws MyException if the input exceeds 10. This serves as a practical demonstration of using exceptions to flag specific errors, triggering control flows through try-catch that enhance robustness. In real-world applications, such signaling enables explicit, controlled handling of domain-specific errors, improving reliability while simplifying error logging and debugging processes. It signifies structured control paths suited to transaction validation or compliance checks in domains like financial applications .

Creating a custom exception is advantageous when an application has specific error conditions that are not semantically represented by Java's built-in exceptions. This enables better error signaling, as the custom exceptions can convey specific, meaningful information relevant to the particular application logic. For instance, application-specific business rules, like eligibility criteria or transaction constraints, can be succinctly represented, making error handling code more readable and maintainable .

The example program demonstrates a custom exception, MyException, thrown when a method's parameter exceeds 10. It uses try-catch to manage normal and exceptional flows. The compute method throws MyException for values greater than 10. When compute(20) is called, it triggers the exception, captured by the catch block, which outputs "Caught MyException[20]". This shows orderly error detection and management, with clear output indicating the error origin and nature .

Overriding methods in a custom exception class allows for enhanced specificity in exception handling, providing detailed, formatted information pertinent to particular errors. For example, overriding toString() in MyException helps by giving a descriptive error message, aiding in troubleshooting. However, it may lead to increased complexity if overused, particularly if numerous or complex methods are overridden unnecessarily. Maintaining consistency and simplicity in exception messages can be harder, leading to potential misinterpretations if details aren't managed carefully .

You might also like