1. Gambaran keseluruhan
Dalam tutorial ini, kita akan membahas asas-asas pengendalian pengecualian di Java serta beberapa gotchanya.
2. Prinsip Pertama
2.1. Apa Itu?
Untuk lebih memahami pengecualian dan pengendalian pengecualian, mari buat perbandingan kehidupan sebenar.
Bayangkan bahawa kami memesan produk secara dalam talian, tetapi semasa dalam perjalanan, terdapat kegagalan dalam penghantaran. Syarikat yang baik dapat mengatasi masalah ini dan mengubah semula pakej kami dengan baik sehingga ia tetap tiba tepat pada waktunya.
Begitu juga, di Java, kod tersebut dapat mengalami kesalahan semasa melaksanakan arahan kami. Pengendalian pengecualian yang baik dapat menangani kesilapan dan mengubah arah program dengan baik untuk memberi pengguna pengalaman positif .
2.2. Mengapa Menggunakannya?
Kami biasanya menulis kod dalam persekitaran yang ideal: sistem fail selalu mengandungi fail kami, rangkaiannya sihat, dan JVM selalu mempunyai memori yang mencukupi. Kadang-kadang kita menyebutnya "jalan bahagia".
Walaupun dalam pengeluaran, sistem fail boleh rosak, rangkaian rosak, dan JVM kehabisan memori. Kesejahteraan kod kami bergantung pada bagaimana ia berurusan dengan "jalan yang tidak bahagia".
Kita mesti menangani syarat-syarat ini kerana ia mempengaruhi aliran aplikasi secara negatif dan membentuk pengecualian :
public static List getPlayers() throws IOException { Path path = Paths.get("players.dat"); List players = Files.readAllLines(path); return players.stream() .map(Player::new) .collect(Collectors.toList()); }
Kod ini memilih untuk tidak menangani IOException , malah menyebarkannya ke tumpukan panggilan. Dalam persekitaran yang ideal, kodnya berfungsi dengan baik.
Tetapi apa yang mungkin berlaku dalam produksi sekiranya pemain.dat hilang?
Exception in thread "main" java.nio.file.NoSuchFileException: players.dat <-- players.dat file doesn't exist at sun.nio.fs.WindowsException.translateToIOException(Unknown Source) at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) // ... more stack trace at java.nio.file.Files.readAllLines(Unknown Source) at java.nio.file.Files.readAllLines(Unknown Source) at Exceptions.getPlayers(Exceptions.java:12) <-- Exception arises in getPlayers() method, on line 12 at Exceptions.main(Exceptions.java:19) <-- getPlayers() is called by main(), on line 19
Tanpa menangani pengecualian ini, program yang sihat mungkin berhenti berjalan sama sekali! Kita perlu memastikan bahawa kod kita mempunyai rancangan untuk mengetahui bila sesuatu menjadi salah.
Perhatikan juga satu lagi faedah di sini untuk pengecualian, dan itu adalah jejak timbunan itu sendiri. Kerana jejak timbunan ini, kita sering dapat menentukan kod yang menyinggung tanpa perlu melampirkan penyahpepijat.
3. Hierarki Pengecualian
Pada akhirnya, pengecualian hanyalah objek Java dengan semuanya meluas dari Throwable :
---> Throwable Exception Error | (checked) (unchecked) | RuntimeException (unchecked)
Terdapat tiga kategori utama syarat luar biasa:
- Pengecualian yang diperiksa
- Pengecualian / Pengecualian waktu tak dicentang
- Kesalahan
Waktu pengecualian dan pengecualian yang tidak diperiksa merujuk kepada perkara yang sama. Kita sering boleh menggunakannya secara bergantian.
3.1. Pengecualian yang diperiksa
Pengecualian yang diperiksa adalah pengecualian yang diperlukan oleh pengendali Java untuk kita atasi. Kita harus secara tidak sengaja membuang pengecualian ke atas timbunan panggilan, atau kita sendiri yang harus mengatasinya. Lebih banyak mengenai kedua-duanya dalam sekejap.
Dokumentasi Oracle memberitahu kami untuk menggunakan pengecualian yang diperiksa apabila kami dapat menjangkakan pemanggil kaedah kami dapat pulih.
Beberapa contoh pengecualian yang diperiksa adalah IOException dan ServletException.
3.2. Pengecualian yang tidak dicentang
Pengecualian yang tidak dicentang adalah pengecualian yang tidak diperlukan oleh penyusun Java untuk kita atasi.
Ringkasnya, jika kita membuat pengecualian yang memperluas RuntimeException , itu tidak akan dicentang; jika tidak, ia akan diperiksa.
Dan walaupun ini terdengar senang, dokumentasi Oracle memberitahu bahawa ada alasan yang baik untuk kedua-dua konsep tersebut, seperti membezakan antara ralat situasional (diperiksa) dan ralat penggunaan (tidak dicentang).
Beberapa contoh pengecualian yang tidak dicentang adalah NullPointerException, IllegalArgumentException, dan SecurityException .
3.3. Kesalahan
Kesalahan menunjukkan keadaan yang serius dan biasanya tidak dapat dipulihkan seperti ketidaksesuaian perpustakaan, pengulangan yang tidak terbatas, atau kebocoran memori.
Dan walaupun mereka tidak memperpanjang RuntimeException , mereka juga tidak dicentang.
Dalam kebanyakan kes, adalah pelik bagi kita untuk menangani, mewujudkan atau memperbesar Kesalahan . Biasanya, kami mahu ini terus berleluasa.
Beberapa contoh kesalahan adalah StackOverflowError dan OutOfMemoryError .
4. Mengendalikan Pengecualian
Di API Java, terdapat banyak tempat di mana keadaan boleh menjadi salah, dan beberapa tempat ini ditandai dengan pengecualian, sama ada dalam tandatangan atau Javadoc:
/** * @exception FileNotFoundException ... */ public Scanner(String fileName) throws FileNotFoundException { // ... }
Seperti yang dinyatakan sedikit sebelumnya, ketika kita menyebut kaedah "berisiko" ini, kita harus menangani pengecualian yang diperiksa, dan kita mungkin menangani yang tidak diperiksa . Java memberi kita beberapa cara untuk melakukan ini:
4.1. balingan
Cara termudah untuk "menangani" pengecualian adalah dengan mengubahnya semula:
public int getPlayerScore(String playerFile) throws FileNotFoundException { Scanner contents = new Scanner(new File(playerFile)); return Integer.parseInt(contents.nextLine()); }
Oleh kerana FileNotFoundException adalah pengecualian yang diperiksa, ini adalah kaedah termudah untuk memuaskan penyusun, tetapi ini bermaksud bahawa sesiapa yang memanggil kaedah kami sekarang juga perlu mengatasinya!
parseInt dapat membuang NumberFormatException , tetapi kerana tidak dicentang , kami tidak perlu mengatasinya.
4.2. cuba tangkap
Sekiranya kita ingin mencuba dan menangani pengecualian itu sendiri, kita boleh menggunakan blok cubaan . Kami dapat mengatasinya dengan memikirkan semula pengecualian kami:
public int getPlayerScore(String playerFile) { try { Scanner contents = new Scanner(new File(playerFile)); return Integer.parseInt(contents.nextLine()); } catch (FileNotFoundException noFile) { throw new IllegalArgumentException("File not found"); } }
Atau dengan melakukan langkah pemulihan:
public int getPlayerScore(String playerFile) { try { Scanner contents = new Scanner(new File(playerFile)); return Integer.parseInt(contents.nextLine()); } catch ( FileNotFoundException noFile ) { logger.warn("File not found, resetting score."); return 0; } }
4.3. akhirnya
Sekarang, ada kalanya kita mempunyai kod yang perlu dijalankan tanpa mengira sama ada pengecualian berlaku, dan di sinilah kata kunci akhirnya masuk.
In our examples so far, there ‘s been a nasty bug lurking in the shadows, which is that Java by default won't return file handles to the operating system.
Certainly, whether we can read the file or not, we want to make sure that we do the appropriate cleanup!
Let's try this the “lazy” way first:
public int getPlayerScore(String playerFile) throws FileNotFoundException { Scanner contents = null; try { contents = new Scanner(new File(playerFile)); return Integer.parseInt(contents.nextLine()); } finally { if (contents != null) { contents.close(); } } }
Here, the finally block indicates what code we want Java to run regardless of what happens with trying to read the file.
Even if a FileNotFoundException is thrown up the call stack, Java will call the contents of finally before doing that.
We can also both handle the exception and make sure that our resources get closed:
public int getPlayerScore(String playerFile) { Scanner contents; try { contents = new Scanner(new File(playerFile)); return Integer.parseInt(contents.nextLine()); } catch (FileNotFoundException noFile ) { logger.warn("File not found, resetting score."); return 0; } finally { try { if (contents != null) { contents.close(); } } catch (IOException io) { logger.error("Couldn't close the reader!", io); } } }
Because close is also a “risky” method, we also need to catch its exception!
This may look pretty complicated, but we need each piece to handle each potential problem that can arise correctly.
4.4. try-with-resources
Fortunately, as of Java 7, we can simplify the above syntax when working with things that extend AutoCloseable:
public int getPlayerScore(String playerFile) { try (Scanner contents = new Scanner(new File(playerFile))) { return Integer.parseInt(contents.nextLine()); } catch (FileNotFoundException e ) { logger.warn("File not found, resetting score."); return 0; } }
When we place references that are AutoClosable in the try declaration, then we don't need to close the resource ourselves.
We can still use a finally block, though, to do any other kind of cleanup we want.
Check out our article dedicated to try-with-resources to learn more.
4.5. Multiple catch Blocks
Sometimes, the code can throw more than one exception, and we can have more than one catch block handle each individually:
public int getPlayerScore(String playerFile) { try (Scanner contents = new Scanner(new File(playerFile))) { return Integer.parseInt(contents.nextLine()); } catch (IOException e) { logger.warn("Player file wouldn't load!", e); return 0; } catch (NumberFormatException e) { logger.warn("Player file was corrupted!", e); return 0; } }
Multiple catches give us the chance to handle each exception differently, should the need arise.
Also note here that we didn't catch FileNotFoundException, and that is because it extends IOException. Because we're catching IOException, Java will consider any of its subclasses also handled.
Let's say, though, that we need to treat FileNotFoundException differently from the more general IOException:
public int getPlayerScore(String playerFile) { try (Scanner contents = new Scanner(new File(playerFile)) ) { return Integer.parseInt(contents.nextLine()); } catch (FileNotFoundException e) { logger.warn("Player file not found!", e); return 0; } catch (IOException e) { logger.warn("Player file wouldn't load!", e); return 0; } catch (NumberFormatException e) { logger.warn("Player file was corrupted!", e); return 0; } }
Java lets us handle subclass exceptions separately, remember to place them higher in the list of catches.
4.6. Union catch Blocks
When we know that the way we handle errors is going to be the same, though, Java 7 introduced the ability to catch multiple exceptions in the same block:
public int getPlayerScore(String playerFile) { try (Scanner contents = new Scanner(new File(playerFile))) { return Integer.parseInt(contents.nextLine()); } catch (IOException | NumberFormatException e) { logger.warn("Failed to load score!", e); return 0; } }
5. Throwing Exceptions
If we don't want to handle the exception ourselves or we want to generate our exceptions for others to handle, then we need to get familiar with the throw keyword.
Let's say that we have the following checked exception we've created ourselves:
public class TimeoutException extends Exception { public TimeoutException(String message) { super(message); } }
and we have a method that could potentially take a long time to complete:
public List loadAllPlayers(String playersFile) { // ... potentially long operation }
5.1. Throwing a Checked Exception
Like returning from a method, we can throw at any point.
Of course, we should throw when we are trying to indicate that something has gone wrong:
public List loadAllPlayers(String playersFile) throws TimeoutException { while ( !tooLong ) { // ... potentially long operation } throw new TimeoutException("This operation took too long"); }
Because TimeoutException is checked, we also must use the throws keyword in the signature so that callers of our method will know to handle it.
5.2. Throwing an Unchecked Exception
If we want to do something like, say, validate input, we can use an unchecked exception instead:
public List loadAllPlayers(String playersFile) throws TimeoutException { if(!isFilenameValid(playersFile)) { throw new IllegalArgumentException("Filename isn't valid!"); } // ... }
Because IllegalArgumentException is unchecked, we don't have to mark the method, though we are welcome to.
Some mark the method anyway as a form of documentation.
5.3. Wrapping and Rethrowing
We can also choose to rethrow an exception we've caught:
public List loadAllPlayers(String playersFile) throws IOException { try { // ... } catch (IOException io) { throw io; } }
Or do a wrap and rethrow:
public List loadAllPlayers(String playersFile) throws PlayerLoadException { try { // ... } catch (IOException io) { throw new PlayerLoadException(io); } }
This can be nice for consolidating many different exceptions into one.
5.4. Rethrowing Throwable or Exception
Now for a special case.
If the only possible exceptions that a given block of code could raise are unchecked exceptions, then we can catch and rethrow Throwable or Exception without adding them to our method signature:
public List loadAllPlayers(String playersFile) { try { throw new NullPointerException(); } catch (Throwable t) { throw t; } }
While simple, the above code can't throw a checked exception and because of that, even though we are rethrowing a checked exception, we don't have to mark the signature with a throws clause.
This is handy with proxy classes and methods. More about this can be found here.
5.5. Inheritance
When we mark methods with a throws keyword, it impacts how subclasses can override our method.
In the circumstance where our method throws a checked exception:
public class Exceptions { public List loadAllPlayers(String playersFile) throws TimeoutException { // ... } }
A subclass can have a “less risky” signature:
public class FewerExceptions extends Exceptions { @Override public List loadAllPlayers(String playersFile) { // overridden } }
But not a “more riskier” signature:
public class MoreExceptions extends Exceptions { @Override public List loadAllPlayers(String playersFile) throws MyCheckedException { // overridden } }
This is because contracts are determined at compile time by the reference type. If I create an instance of MoreExceptions and save it to Exceptions:
Exceptions exceptions = new MoreExceptions(); exceptions.loadAllPlayers("file");
Then the JVM will only tell me to catch the TimeoutException, which is wrong since I've said that MoreExceptions#loadAllPlayers throws a different exception.
Simply put, subclasses can throw fewer checked exceptions than their superclass, but not more.
6. Anti-Patterns
6.1. Swallowing Exceptions
Now, there’s one other way that we could have satisfied the compiler:
public int getPlayerScore(String playerFile) { try { // ... } catch (Exception e) {} // <== catch and swallow return 0; }
The above is calledswallowing an exception. Most of the time, it would be a little mean for us to do this because it doesn't address the issue and it keeps other code from being able to address the issue, too.
There are times when there's a checked exception that we are confident will just never happen. In those cases, we should still at least add a comment stating that we intentionally ate the exception:
public int getPlayerScore(String playerFile) { try { // ... } catch (IOException e) { // this will never happen } }
Another way we can “swallow” an exception is to print out the exception to the error stream simply:
public int getPlayerScore(String playerFile) { try { // ... } catch (Exception e) { e.printStackTrace(); } return 0; }
We've improved our situation a bit by a least writing the error out somewhere for later diagnosis.
It'd be better, though, for us to use a logger:
public int getPlayerScore(String playerFile) { try { // ... } catch (IOException e) { logger.error("Couldn't load the score", e); return 0; } }
While it's very convenient for us to handle exceptions in this way, we need to make sure that we aren't swallowing important information that callers of our code could use to remedy the problem.
Finally, we can inadvertently swallow an exception by not including it as a cause when we are throwing a new exception:
public int getPlayerScore(String playerFile) { try { // ... } catch (IOException e) { throw new PlayerScoreException(); } }
Here, we pat ourselves on the back for alerting our caller to an error, but we fail to include the IOException as the cause. Because of this, we've lost important information that callers or operators could use to diagnose the problem.
We'd be better off doing:
public int getPlayerScore(String playerFile) { try { // ... } catch (IOException e) { throw new PlayerScoreException(e); } }
Notice the subtle difference of including IOException as the cause of PlayerScoreException.
6.2. Using return in a finally Block
Another way to swallow exceptions is to return from the finally block. This is bad because, by returning abruptly, the JVM will drop the exception, even if it was thrown from by our code:
public int getPlayerScore(String playerFile) { int score = 0; try { throw new IOException(); } finally { return score; // <== the IOException is dropped } }
According to the Java Language Specification:
If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and then there is a choice.
If the finally block completes normally, then the try statement completes abruptly for reason R.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
6.3. Using throw in a finally Block
Similar to using return in a finally block, the exception thrown in a finally block will take precedence over the exception that arises in the catch block.
This will “erase” the original exception from the try block, and we lose all of that valuable information:
public int getPlayerScore(String playerFile) { try { // ... } catch ( IOException io ) { throw new IllegalStateException(io); // <== eaten by the finally } finally { throw new OtherException(); } }
6.4. Using throw as a goto
Some people also gave into the temptation of using throw as a goto statement:
public void doSomething() { try { // bunch of code throw new MyException(); // second bunch of code } catch (MyException e) { // third bunch of code } }
This is odd because the code is attempting to use exceptions for flow control as opposed to error handling.
7. Common Exceptions and Errors
Here are some common exceptions and errors that we all run into from time to time:
7.1. Checked Exceptions
- IOException – This exception is typically a way to say that something on the network, filesystem, or database failed.
7.2. RuntimeExceptions
- ArrayIndexOutOfBoundsException – this exception means that we tried to access a non-existent array index, like when trying to get index 5 from an array of length 3.
- ClassCastException – this exception means that we tried to perform an illegal cast, like trying to convert a String into a List. We can usually avoid it by performing defensive instanceof checks before casting.
- IllegalArgumentException – this exception is a generic way for us to say that one of the provided method or constructor parameters is invalid.
- IllegalStateException – This exception is a generic way for us to say that our internal state, like the state of our object, is invalid.
- NullPointerException – This exception means we tried to reference a null object. We can usually avoid it by either performing defensive null checks or by using Optional.
- NumberFormatException – This exception means that we tried to convert a String into a number, but the string contained illegal characters, like trying to convert “5f3” into a number.
7.3. Errors
- StackOverflowError - pengecualian ini bermaksud bahawa jejak timbunan terlalu besar. Ini kadang-kadang boleh berlaku dalam aplikasi besar-besaran; namun, ini biasanya bermaksud bahawa kita mempunyai beberapa pengulangan yang tidak terhingga dalam kod kita.
- NoClassDefFoundError - pengecualian ini bermaksud bahawa kelas gagal dimuat sama ada kerana tidak berada di classpath atau kerana kegagalan dalam permulaan statik.
- OutOfMemoryError - pengecualian ini bermaksud bahawa JVM tidak mempunyai lagi memori yang tersedia untuk diperuntukkan untuk lebih banyak objek. Kadang-kadang, ini disebabkan oleh kebocoran memori.
8. Kesimpulannya
Dalam artikel ini, kami telah mempelajari asas-asas pengendalian pengecualian serta beberapa contoh amalan baik dan buruk.
Seperti biasa, semua kod yang terdapat dalam artikel ini boleh didapati di GitHub!