- The Java Workshop
- David Cuartielles Andreas G?ransson Eric Foster Johnson
- 1406字
- 2021-06-11 13:05:26
A Simple Exception Example
Start by provoking a simple exception in your code. First, type in the following program in the Integrated Development Environment (IDE) and execute it:
public class Example01 {
public static void main(String[] args) {
// declare a string with nothing inside
String text = null;
// you will see this at the console
System.out.println("Go Java Go!");
// null'ed strings should crash your program
System.out.println(text.length());
// you will never see this print
System.out.println("done");
}
}
Here is the output:
Go Java Go!
Exception in thread "main" java.lang.NullPointerException
at Example01.main(Example01.java:11)
Process finished with exit code 1
The previous code listing shows how the program starts executing a command that works fine. The sentence Go Java Go! is printed on the console, but then a NullPointerException shows up, highlighting that something exceptional happened. In this case, we tried to print the length of a string initiated to null by calling text.length(). Since there is no length to be calculated (that is, we don't even have an empty string), either System.out.println() or text.length() provoked the exception. Additionally, there was an error at that point, so the program exited and the final call to System.out.println("done") was not executed. You could try to separate both commands to see what the outcome will be:
// null'ed strings should crash your program
int number = text.length();
System.out.println(number);
Here is the output:
Go Java Go!
Exception in thread "main" java.lang.NullPointerException
at Example01.main(Example01.java:11)
Process finished with exit code 1
If you check the line numbers in the IDE, you will see that the exception takes place on the line where we are trying to get the length of the string. Now that we know the cause of the problem, there are two ways around this issue: either we fix the data (note that there will be situations where this will be impossible), or we include a countermeasure in our code to detect the exceptions and then handle or ignore them. The action of handling an unexpected event is what we call catching the exception. On the other hand, bypassing the event is called throwing the exception. Later in the chapter, we will explore different ways of doing both of these actions, as well as good practices for when writing code-handling exceptions.
However, before learning about how to avoid or handle exceptions, let's provoke some more. Almost every Java API includes the definition of an exception that can help to propagate errors towards the main class, and thus the developer. In that way, it will be possible to avoid situations where the code will break in front of the user's eyes.
The exceptions covered by the Java APIs are what we call built-in exceptions. It is also possible to create your own when you define a class. Talking about classes, let's try to get a character from a non-existing location within an object instantiated from String and see what happens:
public class Example02 {
public static void main(String[] args) {
// declare a string of a fixed length
String text = "I <3 bananas"; // 12 characters long
// provoke an exception
char character = text.charAt(15); // get the 15th element
// you will never see this print
System.out.println("done");
}
}
The IDE will respond with the following:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 15
at java.lang.String.charAt(String.java:658)
at Example02.main(Example02.java:8)
Process finished with exit code 1
Note that the text variable is only 12 characters long. When trying to extract the 15th character, the IDE will issue an exception and terminate the program. In this case, we got one called StringOutOfBoundsException. There are many different types of built-in exceptions.
Here's a list of the various types of exceptions:
- NullPointerException
- StringOutOfBoundsException
- ArithmeticException
- ClassCastException
- IllegalArgumentException
- IndexOutOfBoundsException
- NumberFormatException
- IllegalAccessException
- InstantiationException
- NoSuchMethodException
As you can see, the names of the different exceptions are quite descriptive. When you get one, it should be quite easy to figure out where to find more information about it within the Java documentation in order to mitigate the problem. We classify exceptions as checked or unchecked:
- Checked exceptions: These are highlighted during compilation. In other words, your program will not make it to the end of the compilation process, and therefore you will not be able to run it.
- Unchecked exceptions: These show up during program execution; therefore, we also call them runtime exceptions. The examples that have been shown in this chapter so far (NullPointerException and StringOutOfBoundsException) are both unchecked.
Why Two Types of Exception?
There are two possibilities for exceptions: either we, as developers, make a mistake and don't realize that our way of handling data is going to produce an error (such as when we are trying to get the length of an empty string or when we are dividing a number by zero), or the error happens because we are uncertain about the nature of the data we will be gathering during an exchange with something external to our program (such as when getting parameters from the CLI and they are of the wrong type). In cases like the first one, checked exceptions make more sense. The second scenario is the reason why we need unchecked exceptions. In this second case, we should develop strategies to handle potential threats to the proper execution of the program.
Making an example of a checked exception is slightly more complicated because we have to anticipate things that will not be introduced in depth until a later chapter. However, we consider that the following example, which displays an example of IOException, is simple enough even if it includes a couple of classes that haven't been touched on in the book yet:
import java.nio.file.*;
import java.util.*;
public class Example03 {
public static void main(String[] args) {
// declare a list that will contain all of the files
// inside of the readme.txt file
List<String> lines = Collections.emptyList();
// provoke an exception
lines = Files.readAllLines(Paths.get("readme.txt"));
// you will never see this print
Iterator<String> iterator = lines.iterator();
while (iterator.hasNext())
System.out.println(iterator.next());
}
}
The newest thing in this code listing is the use of java.nio.file.*. This is an API that includes classes and methods to manage files, among other things. The goal of this program is to read a whole text file called readme.txt into a list that will then be printed using an iterator, as we saw in Chapter 4, Collections, Lists, and Java's Built-In APIs.
This is a case where a checked exception could occur when calling Files.readAllLines() if there is no file to be read because of, for example, having a wrongly declared filename. The IDE knows this and, therefore, it flags that there is a potential risk.
Note how the IDE displays a warning from the moment we write the code. Furthermore, when trying to compile the program, the IDE will respond with the following:
Error:(11, 35) java: unreported exception java.io.IOException; must be caught or declared to be thrown
Catching and throwing are the two strategies that you can use to avoid exceptions. We will talk about them in more detail later in the chapter.
- 微服務(wù)設(shè)計(第2版)
- 深入核心的敏捷開發(fā):ThoughtWorks五大關(guān)鍵實踐
- CMDB分步構(gòu)建指南
- 程序員面試筆試寶典
- 人人都懂設(shè)計模式:從生活中領(lǐng)悟設(shè)計模式(Python實現(xiàn))
- SharePoint Development with the SharePoint Framework
- Building Serverless Applications with Python
- Java程序員面試筆試寶典(第2版)
- Mastering ArcGIS Enterprise Administration
- GameMaker Essentials
- Web編程基礎(chǔ):HTML5、CSS3、JavaScript(第2版)
- Python應(yīng)用與實戰(zhàn)
- Python數(shù)據(jù)科學(xué)實踐指南
- Java 11 and 12:New Features
- Spring Boot 2+Thymeleaf企業(yè)應(yīng)用實戰(zhàn)