Java creating new exception

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.

Источник

Читайте также:  Php получить только числа

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.

Источник

Java creating new exception

  • 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
Читайте также:  border-collapse

Источник

How to create custom exceptions in Java

In the article Getting Started with Exception Handling in Java, you know how to catch throw and catch exceptions which are defined by JDK such as IllegalArgumentException , IOException , NumberFormatException , etc.

What if you want to throw your own exceptions? Imagine you’re writing a student management program and you want to throw StudentException , StudentNotFoundException , StudentStoreException and the like?

So it’s time to create new exceptions of your own.

We will call JDK’s exceptions built-in exceptions and call our own exceptions custom exceptions.

Let me tell you this: Writing custom exceptions in Java is very easy, but the important thing is, you should ask yourself this question:

1. Why do I need custom exceptions?

The answer could be very simple: When you couldn’t find any relevant exceptions in the JDK, it’s time to create new ones of your own.

By looking at the names of the exceptions to see if its meaning is appropriate or not. For example, the IllegalArgumentException is appropriate to throw when checking parameters of a method; the IOException is appropriate to throw when reading/writing files.

From my experience, most of the cases we need custom exceptions for representing business exceptions which are, at a level higher than technical exceptions defined by JDK. For example: InvalidAgeException , LowScoreException , TooManyStudentsException , etc.

2. Writing your own exception class

  • Create a new class whose name should end with Exception like ClassNameException . This is a convention to differentiate an exception class from regular ones.
  • Make the class extends one of the exceptions which are subtypes of the java.lang.Exception class. Generally, a custom exception class always extends directly from the Exception class.
  • Create a constructor with a String parameter which is the detail message of the exception. In this constructor, simply call the super constructor and pass the message.
public class StudentNotFoundException extends Exception < public StudentNotFoundException(String message) < super(message); >>

And the following example shows the way a custom exception is used is nothing different than built-in exception:

public class StudentManager < public Student find(String studentID) throws StudentNotFoundException < if (studentID.equals("123456")) < return new Student(); >else < throw new StudentNotFoundException( "Could not find student with ID " + studentID); >> >
public class StudentTest < public static void main(String[] args) < StudentManager manager = new StudentManager(); try < Student student = manager.find("0000001"); >catch (StudentNotFoundException ex) < System.err.print(ex); >> >
StudentNotFoundException: Could not find student with ID 0000001

3. Re-throwing an exception which is wrapped in a custom exception

It’s a common practice for catching a built-in exception and re-throwing it via a custom exception. To do so, let add a new constructor to our custom exception class. This constructor takes two parameters: the detail message and the cause of the exception. This constructor is implemented in the Exception class as following:

Читайте также:  Язык питон 36 оператор вывода ответы

public Exception(String message, Throwable cause)

Besides the detail message, this constructor takes a Throwable ’s subclass which is the origin (cause) of the current exception. For example, create the StudentStoreException class as following:

public class StudentStoreException extends Exception < public StudentStoreException(String message, Throwable cause) < super(message, cause); >>
public void save(Student student) throws StudentStoreException < try < // execute SQL statements.. >catch (SQLException ex) < throw new StudentStoreException("Failed to save student", ex); >>

Here, suppose that the save() method stores the specified student information into a database using JDBC. The code can throw SQLException . We catch this exception and throw a new StudentStoreException which wraps the SQLException as its cause. And it’s obvious that the save() method declares to throw StudentStoreException instead of SQLException .

So what is the benefit of re-throwing exception like this?

Why not leave the original exception to be thrown?

Well, the main benefit of re-throwing exception by this manner is adding a higher abstraction layer for the exception handling, which results in more meaningful and readable API. Do you see StudentStoreException is more meaningful than SQLException , don’t you?

However, remember to include the original exception in order to preserve the cause so we won’t lose the trace when debugging the program when the exception occurred.

And the following code demonstrates handling the StudentStoreException above:

StudentManager manager = new StudentManager(); try < manager.save(new Student()); >catch (StudentStoreException ex)

References:

Other Java Exception Handling Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Оцените статью