- Make an exception class in java
- Creating Exception Classes
- An Example
- Choosing a Superclass
- Make an exception class in java
- Class Exception
- Constructor Summary
- Method Summary
- Methods declared in class java.lang.Throwable
- Methods declared in class java.lang.Object
- Constructor Details
- Exception
- Exception
- Exception
- Exception
- Exception
- How to Create an Exception Class in Java
- Related Articles
- Training Options
- Course Catalog
Make an exception class in java
- Introduction to Java
- The complete History of Java Programming Language
- C++ vs Java vs Python
- How to Download and Install Java for 64 bit machine?
- Setting up the environment in Java
- How to Download and Install Eclipse on Windows?
- JDK in Java
- How JVM Works – JVM Architecture?
- Differences between JDK, JRE and JVM
- Just In Time Compiler
- Difference between JIT and JVM in Java
- Difference between Byte Code and Machine Code
- How is Java platform independent?
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else
- Java if-else-if ladder with Examples
- Loops in Java
- For Loop in Java
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- Usage of Break keyword in Java
- return keyword in Java
- Object Oriented Programming (OOPs) Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects in Java
- Naming Conventions in Java
- Java Methods
- Access Modifiers in Java
- Java Constructors
- Four Main Object Oriented Programming Concepts of Java
- Inheritance in Java
- Abstraction in Java
- Encapsulation in Java
- Polymorphism in Java
- Interfaces in Java
- ‘this’ reference in Java
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.
Make an exception class in 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()); >>
Class Exception
The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor’s throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.
Constructor Summary
Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.
Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause ).
Method Summary
Methods declared in class java.lang.Throwable
Methods declared in class java.lang.Object
Constructor Details
Exception
Constructs a new exception with null as its detail message. The cause is not initialized, and may subsequently be initialized by a call to Throwable.initCause(java.lang.Throwable) .
Exception
Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently be initialized by a call to Throwable.initCause(java.lang.Throwable) .
Exception
Constructs a new exception with the specified detail message and cause. Note that the detail message associated with cause is not automatically incorporated in this exception’s detail message.
Exception
Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause ). This constructor is useful for exceptions that are little more than wrappers for other throwables (for example, PrivilegedActionException ).
Exception
protected Exception (String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)
Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
How to Create an Exception Class in Java
Java has many built-in exception classes, such as NullPointerException and IllegalArgumentException . At times however, you might want to create your own exception class. For example, as opposed to throwing IllegalArgumentException when a 0 is detected as a divisor during a division operation, you might wish to throw a DivideByZeroException . This exception class does not exist in the Java core API, but you can create one yourself. The seven steps below will show you how to create an exception class in Java.
- First, you will create the custom exception class. Open your text editor and type in the following Java statements:
The class extends the Exception class that is defined in the Java core API (in the package is java.lang ). When extending Exception you are defining a «checked» exception, i.e., an exception that must be caught or thrown. A constructor is provided that passes the message argument to the super class Exception . The Exception class supports a message property.
- Save your file as DivideByZeroException.java .
- Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter .
- Now you will create the program to test your new exception class. Open your text editor and type in the following Java statements:
Notice that the divideInt method must provide a throw clause because the method potentially throws the DivideByZeroException . To create the exception object, the program uses the throw keyword followed by the instantiation of the exception object. At runtime, the throw clause will terminate execution of the method and pass the exception to the calling method.
- Save your file as TestDivideByZeroException.java .
- Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter .
- Type in the command to run your program and hit Enter .
The first call to the divideInt method is successful. The second call, using a divisor of 0, causes the DivideByZeroException to be thrown in the divideInt method. The message passed to the constructor is displayed in the output.
Related Articles
- How to Check Object Type in Java
- How to Create a Jar File in Java
- How to Compile Packages in Java
- How to Throw an Exception in Java
- How to Create an Exception Class in Java (this article)
- How to Use the super Keyword to Call a Base Class Constructor in Java
- How to Use the Comparator.comparing Method in Java 8
- How to Use System.in in Java
- How to Call an Interface Method in Java
- How to Add a Time Zone in the Java 8 Date/Time API
- How to Rethrow an Exception in Java
- How to Use the instanceof Operator with a Generic Class in Java
- How to Instantiate an Object in Java
- How to Filter Distinct Elements from a Collection in Java 8
- How to Create a Derived Class in Java
- How to Skip Elements with the Skip Method in Java 8
- How to Create a Java Bean
- How to Implement an Interface in Java
- How to Compare Two Objects with the equals Method in Java
- How to Set PATH from JAVA_HOME
- How to Prevent Race Conditions in Java 8
- How to Write a Block of Code in Java
- How to Display the Contents of a Directory in Java
- How to Group and Partition Collectors in Java 8
- How to Create a Reference to an Object in Java
- How to Reduce the Size of the Stream with the Limit Method in Java 8
- How to Write an Arithmetic Expression in Java
- How to Format Date and Time in the Java 8 Date/Time API
- How to Use Comparable and Comparator in Java
- How to Break a Loop in Java
- How to Use the this Keyword to Call Another Constructor in Java
- How to Write a Unit Test in Java
- How to Declare Variables in Java
- How to Override Base Class Methods with Derived Class Methods in Java
- How to Use Serialized Objects in Java
- How to Write Comments in Java
- How to Implement Functional Interfaces in Java 8
- How to Write Type Parameters with Multiple Bounds in Java
- How to Add Type and Repeating Annotations to Code in Java 8
- How to Use Basic Generics Syntax in Java
- How to Map Elements Using the Map Method in Java 8
- How to Work with Properties in Java
- How to Write while and do while Loops in Java
- How to Use the finally Block in Java
- How to Write for-each Loops in Java
- How to Create a Method in Java
- How to Continue a Loop in Java
- How to Handle Java Files with Streams
- How to Create an Interface Definition in Java
- How Default Base Class Constructors Are Used with Inheritance