How to create custom exceptions in Java? [closed]
It’s difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
3 Answers 3
To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception . For example:
public class FooException extends Exception < public FooException() < super(); >public FooException(String message) < super(message); >public FooException(String message, Throwable cause) < super(message, cause); >public FooException(Throwable cause) < super(cause); >>
Methods that can potentially throw or propagate this exception must declare it:
public void calculate(int i) throws FooException, IOException;
. and code calling this method must either handle or propagate this exception (or both):
try < int i = 5; myObject.calculate(5); >catch(FooException ex) < // Print error and terminate application. ex.printStackTrace(); System.exit(1); >catch(IOException ex) < // Rethrow as FooException. throw new FooException(ex); >
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 ):
public class FooRuntimeException extends RuntimeException
Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.
public void calculate(int i) < if (i < 0) < throw new FooRuntimeException("i < 0: " + i); >>
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.
The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable . Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be «handled» by the programmer (e.g. OutOfMemoryError ). Likewise you should avoid catching Throwable , which could result in you catching Error s in addition to Exception s.
New class exception java
Хотя имеющиеся в стандартной библиотеке классов Java классы исключений описывают большинство исключительных ситуаций, которые могут возникнуть при выполнении программы, все таки иногда требуется создать свои собственные классы исключений со своей логикой.
Чтобы создать свой класс исключений, надо унаследовать его от класса Exception. Например, у нас есть класс, вычисляющий факториал, и нам надо выбрасывать специальное исключение, если число, передаваемое в метод, меньше 1:
class Factorial < public static int getFactorial(int num) throws FactorialException< int result=1; if(num<1) throw new FactorialException("The number is less than 1", num); for(int i=1; i<=num;i++)< result*=i; >return result; > > class FactorialException extends Exception < private int number; public int getNumber()public FactorialException(String message, int num) < super(message); number=num; >>
Здесь для определения ошибки, связанной с вычислением факториала, определен класс FactorialException , который наследуется от Exception и который содержит всю информацию о вычислении. В конструкторе FactorialException в конструктор базового класса Exception передается сообщение об ошибке: super(message) . Кроме того, отдельное поле предназначено для хранения числа, факториал которого вычисляется.
Для генерации исключения в методе вычисления факториала выбрасывается исключение с помощью оператора throw: throw new FactorialException(«Число не может быть меньше 1», num) . Кроме того, так как это исключение не обрабатывается с помощью try..catch, то мы передаем обработку вызывающему методу, используя оператор throws: public static int getFactorial(int num) throws FactorialException
Теперь используем класс в методе main:
public static void main(String[] args) < try< int result = Factorial.getFactorial(6); System.out.println(result); >catch(FactorialException ex) < System.out.println(ex.getMessage()); System.out.println(ex.getNumber()); >>
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.
Note: For readable code, it’s good practice to append the string Exception to the names of all classes that inherit (directly or indirectly) from the Exception class.