English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn about exceptions in Java. We will introduce errors, exceptions, and different types of exceptions in Java.
An exception is an unexpected event that occurs during program execution. It affects the program instruction flow, resulting in an abnormal termination of the program.
There are many reasons for exceptions. These include:
Invalid user input
Device failure
Lost network connection
Physical limitations (insufficient disk memory)
Code error
Opening an unavailable file
This is a simplified diagram of the exception hierarchy in Java.
From the above figure, it can be seen that the Throwable class is the root class in the hierarchy.
Note that the hierarchy is divided into two branches: Error (Error) and Exception (Exception).
ErrorIndicates an irrecoverable situation, such as Java Virtual Machine (JVM) memory不足, memory leak, stack overflow error, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer, and we should not attempt to handle errors.
A program can catch and handleException.
When an exception occurs within a method, it creates an object. This object is called the exception object.
It contains information about the exception, such as the name and description of the exception, and the state of the program when the exception occurs.
In the next tutorial, we will learn how to handle these exceptions. In this tutorial, we will focus on different types of exceptions in Java.
The exception hierarchy also has two branches: RuntimeException and IOException.
OneRuntime exceptionsOccurred due to programming errors. They are also known asNon-checked exceptions.
These exceptions are not checked at compile time, but at runtime. Some common runtime exceptions include:
API usage error - IllegalArgumentException
Access by null pointer (fehlende Initialisierung von Variablen)- NullPointerException
Überbereichszugriff auf Array - ArrayIndexOutOfBoundsException
Zahlen durch 0 teilen - ArithmeticException
Sie können so denken:Wenn dies ein Laufzeitfehler ist, liegt es an dir。
wenn vor dem Verwenden eines Variablen überprüft wird, ob die Variable initialisiert wurde, wird keine NullPointerException auftreten.
wenn der Arrayindex gemäß den Arraygrenzen getestet wird, wird keine ArrayIndexOutOfBoundsException auftreten.
IOException wird auchÜberprüfungsfehler. Sie werden vom Compiler bei der Kompilierung überprüft und dem Programmierer eine Behandlung dieser Ausnahmen vorgeschlagen.
Einige Beispiele für Überprüfungsfehler sind:
Das Versuchen, eine Datei zu öffnen, die nicht existiert, führt zu einer FileNotFoundException
Inhalte zu lesen, die über dem Dateiende liegen
Jetzt, da wir Ausnahmen verstanden haben, werden wir im nächsten Tutorial lernenAusnahmen behandeln.