Home  >  Article  >  Java  >  Subclassing Exceptions in Java

Subclassing Exceptions in Java

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 07:59:03817browse

Custom Exceptions:

  • Java allows you to create your own exceptions, in addition to internal exceptions, to handle application-specific errors.
  • To create a custom exception, simply define a subclass of Exception, which is a subclass of Throwable.

Simple Deployment:

  • Custom exceptions do not need additional methods to be valid; the creation of a new class already allows its use in error handling.
  • The Exception class inherits methods from the Throwable class, which can be used or overridden as needed.

Custom Exception Example:

  • The NonIntResultException exception is created to be thrown when dividing two integers results in a non-integer value.
  • The class contains two fields (n and d) to store the values ​​that caused the error, as well as a constructor to initialize them.
  • The toString() method is overridden to provide a detailed description of the exception.

Example Code:
An array number and another denom contain values ​​that will be divided.
In the loop, it checks whether the value in number is odd, and if so, it throws a NonIntResultException.

Try-catch blocks are used to catch and handle exceptions:

  • ArithmeticException: catches division by zero.
  • ArrayIndexOutOfBoundsException: captures index outside the bounds of the array.
  • NonIntResultException: catches divisions that result in fractional values.

Program Exit:

  • Displays the division result if it is valid.
  • Displays error messages depending on the type of exception:
  • "Can't divide by Zero!" for divisions by zero.
  • "No matching elements found." for indexes outside the array.
  • "Result of [n] / [d] is non-integer." for divisions that do not result in integers.

Criando Subclasses de Exceções em Java

The above is the detailed content of Subclassing Exceptions in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn