Make an exception class in java

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.

Читайте также:  Order by field java

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 ).

Читайте также:  Local class incompatible stream classdesc serialversionuid in java

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.

  1. First, you will create the custom exception class. Open your text editor and type in the following Java statements:Java Source for Create an Exception ClassThe 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.
  2. Save your file as DivideByZeroException.java .
  3. 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 .Compile Source for Create Exception
  4. Now you will create the program to test your new exception class. Open your text editor and type in the following Java statements:Java Source for Testing Exception ClassNotice 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.
  5. Save your file as TestDivideByZeroException.java .
  6. 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 .Compile Source for Test Create Exception
  7. Type in the command to run your program and hit Enter .Run for Test Create ExceptionThe 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.
Читайте также:  Javascript node js введение
  1. How to Check Object Type in Java
  2. How to Create a Jar File in Java
  3. How to Compile Packages in Java
  4. How to Throw an Exception in Java
  5. How to Create an Exception Class in Java (this article)
  6. How to Use the super Keyword to Call a Base Class Constructor in Java
  7. How to Use the Comparator.comparing Method in Java 8
  8. How to Use System.in in Java
  9. How to Call an Interface Method in Java
  10. How to Add a Time Zone in the Java 8 Date/Time API
  11. How to Rethrow an Exception in Java
  12. How to Use the instanceof Operator with a Generic Class in Java
  13. How to Instantiate an Object in Java
  14. How to Filter Distinct Elements from a Collection in Java 8
  15. How to Create a Derived Class in Java
  16. How to Skip Elements with the Skip Method in Java 8
  17. How to Create a Java Bean
  18. How to Implement an Interface in Java
  19. How to Compare Two Objects with the equals Method in Java
  20. How to Set PATH from JAVA_HOME
  21. How to Prevent Race Conditions in Java 8
  22. How to Write a Block of Code in Java
  23. How to Display the Contents of a Directory in Java
  24. How to Group and Partition Collectors in Java 8
  25. How to Create a Reference to an Object in Java
  26. How to Reduce the Size of the Stream with the Limit Method in Java 8
  27. How to Write an Arithmetic Expression in Java
  28. How to Format Date and Time in the Java 8 Date/Time API
  29. How to Use Comparable and Comparator in Java
  30. How to Break a Loop in Java
  31. How to Use the this Keyword to Call Another Constructor in Java
  32. How to Write a Unit Test in Java
  33. How to Declare Variables in Java
  34. How to Override Base Class Methods with Derived Class Methods in Java
  35. How to Use Serialized Objects in Java
  36. How to Write Comments in Java
  37. How to Implement Functional Interfaces in Java 8
  38. How to Write Type Parameters with Multiple Bounds in Java
  39. How to Add Type and Repeating Annotations to Code in Java 8
  40. How to Use Basic Generics Syntax in Java
  41. How to Map Elements Using the Map Method in Java 8
  42. How to Work with Properties in Java
  43. How to Write while and do while Loops in Java
  44. How to Use the finally Block in Java
  45. How to Write for-each Loops in Java
  46. How to Create a Method in Java
  47. How to Continue a Loop in Java
  48. How to Handle Java Files with Streams
  49. How to Create an Interface Definition in Java
  50. How Default Base Class Constructors Are Used with Inheritance

Training Options

Course Catalog

Источник

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