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, leading to an abnormal termination of the program.
There are many reasons for exceptions. Among them are:
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 leaks, stack overflow errors, library incompatibility, infinite recursion, and so on.
Errors are usually beyond the control of the programmer, and we should not attempt to handle errors.
The 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.
ARuntime exceptionsOccurred due to programming errors. They are also known asUnchecked exceptions.
These exceptions are not checked at compile time, but at runtime. Some common runtime exceptions include:
Improper API usage - IllegalArgumentException
Null pointer access (missing variable initialization)- NullPointerException
Out-of-bounds array access - ArrayIndexOutOfBoundsException
Dividing a number by 0 - ArithmeticException
You can think of it like this:If this is a runtime exception, it is your mistake。
No NullPointerException will occur if the variable is checked whether it has been initialized before using it.
No ArrayIndexOutOfBoundsException will occur if the array index is tested based on the array boundary.
IOException is also known asChecked Exceptions. They are checked by the compiler at compile time and prompt the programmer to handle these exceptions.
Some examples of checked exceptions are:
Attempting to open a non-existent file will cause FileNotFoundException
Attempting to read content beyond the end of the file
Now that we have understood exceptions, we will learn in the next tutorialException Handling.