Home >Java >JavaBase >What does exception in java mean?

What does exception in java mean?

王林
王林Original
2019-11-11 13:41:217210browse

What does exception in java mean?

What is an exception?

Exception in Java, also known as exception, is an event that occurs during program execution, which interrupts the normal instruction flow of the executing program. In order to handle running errors in the program promptly and effectively, exception classes must be used.

Exception example:

In order to better understand what an exception is, let’s look at a very simple Java program. The following sample code allows the user to enter an integer within 1~3, and prompts an input error in other cases.

What does exception in java mean?

Under normal circumstances, the user will enter a number between 1 and 3 according to the system prompts. However, if the user does not input as required, for example, enters a letter "a", an exception will occur when the program is run, and the running results are as follows.

What does exception in java mean?

Cause of exception:

There are three main reasons why an exception occurs in Java:

(1) Java internal error exception, exception generated by Java virtual machine.

(2) Exceptions caused by errors in the written program code, such as null pointer exceptions, array out-of-bounds exceptions, etc. This kind of exception is called an unchecked exception, and it is generally necessary to handle these exceptions centrally in certain classes.

(3) Exceptions manually generated through the throw statement. This exception is called a checked exception and is generally used to inform the caller of the method some necessary information.

Exception usage principles:

Java exceptions force users to consider the robustness and security of the program. Exception handling should not be used to control the normal flow of the program. Its main function is to capture exceptions that occur when the program is running and handle them accordingly. When writing code to handle exceptions that may occur in a certain method, you can follow the following three principles:

(1) Use the try catch statement in the current method declaration to catch exceptions.

(2) When a method is overridden, the method that overrides it must throw the same exception or a subclass of the exception.

(3) If the parent class throws multiple exceptions, the overriding method must throw a subset of those exceptions and cannot throw new exceptions.

Recommended tutorial: Java tutorial

The above is the detailed content of What does exception in java mean?. 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