Как создать свое исключение java

от admin

Creating Exception Classes

When faced with choosing the type of exception to throw, you can either use one written by someone else — the Java platform provides a lot of exception classes you can use — or you can write one of your own. You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.

  • Do you need an exception type that isn't represented by those in the Java platform?
  • Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
  • Does your code throw more than one related exception?
  • If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?

An Example

Suppose you are writing a linked list class. The class supports the following methods, among others:

  • objectAt(int n) — Returns the object in the n th position in the list. Throws an exception if the argument is less than 0 or more than the number of objects currently in the list.
  • firstObject() — Returns the first object in the list. Throws an exception if the list contains no objects.
  • indexOf(Object o) — Searches the list for the specified Object and returns its position in the list. Throws an exception if the object passed into the method is not in the list.

The linked list class can throw multiple exceptions, and it would be convenient to be able to catch all exceptions thrown by the linked list with one exception handler. Also, if you plan to distribute your linked list in a package, all related code should be packaged together. Thus, the linked list should provide its own set of exception classes.

The next figure illustrates one possible class hierarchy for the exceptions thrown by the linked list.

Example exception class hierarchy.

Choosing a Superclass

Any Exception subclass can be used as the parent class of LinkedListException . However, a quick perusal of those subclasses shows that they are inappropriate because they are either too specialized or completely unrelated to LinkedListException . Therefore, the parent class of LinkedListException should be Exception .

Most applets and applications you write will throw objects that are Exception s. Error s are normally used for serious, hard errors in the system, such as those that prevent the JVM from running.

Как создать свое исключение java

Хотя имеющиеся в стандартной библиотеке классов Java классы исключений описывают большинство исключительных ситуаций, которые могут возникнуть при выполнении программы, все таки иногда требуется создать свои собственные классы исключений со своей логикой.

Чтобы создать свой класс исключений, надо унаследовать его от класса Exception. Например, у нас есть класс, вычисляющий факториал, и нам надо выбрасывать специальное исключение, если число, передаваемое в метод, меньше 1:

Здесь для определения ошибки, связанной с вычислением факториала, определен класс FactorialException , который наследуется от Exception и который содержит всю информацию о вычислении. В конструкторе FactorialException в конструктор базового класса Exception передается сообщение об ошибке: super(message) . Кроме того, отдельное поле предназначено для хранения числа, факториал которого вычисляется.

Для генерации исключения в методе вычисления факториала выбрасывается исключение с помощью оператора throw: throw new FactorialException(«Число не может быть меньше 1», num) . Кроме того, так как это исключение не обрабатывается с помощью try..catch, то мы передаем обработку вызывающему методу, используя оператор throws: public static int getFactorial(int num) throws FactorialException

What are Exceptions in JAVA?

Exceptions are the runtime error in the Java Program. Any unexpected or unwanted event that can break or disturb the usual execution flow of the program is termed an exception.

For Example-

Consider application accessing the files from the internet, processing it, and performing any task. In this, the normal flow of the program will be-

  • Access the files from the Internet.
  • Performs Processing/Calculations on that file.
  • Use that processed file for output.

Now suppose there is any unexpected event that occurs like — The Internet didn’t connect, File received from the internet is corrupted, etc. Then how the application performs processing on that file. This can be the situation where the application cannot proceed further because we haven’t instructed the application that what to do in this kind of situation. So the application will terminate abnormally. This is one of the reasons, and there can be many reasons for abnormal termination of the program.

Here that unexpected event is the exception. And to avoid this abnormal behavior of the application, we need to explicitly define the application, and how it should have continued the execution, which is called Exception Handling.

Now for the same program. The application’s execution flow using exception handling will be —

  • Access the files from the internet.
  • If the file is received successfully then perform calculation/processing on that file.
  • Otherwise, display the error.

By adding the handler for exceptions, the application will not terminate abnormally. JAVA uses try & catch keywords for exception handling.

What are Custom Exceptions in JAVA-

There are 2 types of Exceptions in Java. Checked and Unchecked Exceptions. And Java has certain classes defined for this type of exception like — ArtithmeticException, FileNotFoundException, ArrayIndexOutOfBoundExeption, etc. but these predefined exception classes are sometimes not sufficient for the application that we make. So we need to explicitly define the program with our customized exceptions that are required to be handled.

Читать:
Google files что это за приложение

Example — Consider the application for online shopping in which customers can purchase the products. Suppose, any customer tries to add a single product to a cart with too many quantities, then it must not happen. We need to stop customers to add the same product to the cart with more than the defined quantity per customer without affecting the execution of the program. So here any predefined exception classes are not available that we can use to avoid this. Here we must have to define a custom exception class to handle that and display the error to the user.

These custom exceptions are mostly used for the business logic of the application. It helps the developers to avoid writing too many if-else blocks, and organize the application code.

Steps to Create Custom Exceptions in JAVA-

  1. Create a class with the name as per the requirement. And this class should inherit the Exception class.

public class OverLimitQuantityException extends Exception<
>

2. Create a constructor of the custom exception class.

public class OverLimitQuantityException extends Exception <
OverLimitQuantityException() <
>
OverLimitQuantityException(String message) <
>
>

Note — The constructor can be parameterized or non-parameterized. It is based on the message you need to pass before throwing the exception. Here for the example purpose, we have taken 2 constructors.

3. Call the parent class (Exception Class) constructor from the custom exception class constructor using the super() keyword.

public class OverLimitQuantityException extends Exception <
OverLimitQuantityException() <
super();
>
OverLimitQuantityException(String message) <
super(message);
>

Note — In the parameterized constructor we are passing the message to be shown as the exception message are passed to the exception class constructor.

With these steps, the custom exception is created and ready to use in the program. Now to create the object of this custom exception in the program, we are required to use the throw keyword, which will create the object of the custom exception and initiate passing the object to the JVM for raising the exception. So it should be like —

if(Condition for raising Custom Exception) <
throw new OverLimitQuantityException(“You Cannot purchase more than x quantity”);
>

Note — The method having these conditions must have to be declared as Checked Exception using the throws CustomException with the method declaration and hence it will become checked exception, so it must have to handle with a try & catch keyword with calling the method that throws this exception.

Now let’s understand these in working —

Explanation —

We have declared the custom exception class with a constructor that initiates the exception by calling the Exception class constructor using the super() keyword. Then we have a method that adds the quantity to the cart and that method throws the custom exception based on the check of quantity. While this method throws the exception so we need to explicitly define it in the method declaration. This method throws the exception if the quantity customer wants to add is more than 2. And during the method call, we need to handle it with try & catch that helps recognize that exception raised

Conclusion —

Custom exceptions are exceptions that are explicitly defined by the programmer in the program. It can be created by defining the class inheriting from the base Exception class.

Tips for Creating Custom Exception-

  • Define a class name ending with the Exception keyword, Although it’s not important but is a good programming practice.
  • Pass a recognizable Exception Message because it becomes easy for other developers in understanding.

The main benefit of the custom exception is that it helps the programmer write clean business logic and handle that error accordingly. It avoids writing unnecessary multiple if-else conditions in the program.

How to create custom exceptions in Java? [closed]

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception . For example:

Methods that can potentially throw or propagate this exception must declare it:

. and code calling this method must either handle or propagate this exception (or both):

You’ll notice in the above example that IOException is caught and rethrown as FooException . This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don’t want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception ):

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

Похожие статьи