![]() |
An IOException in Java occurs when we try to perform some input or output tasks and then some issues occur. Programmers need to handle this issue explicitly with a piece of code that executes when an issue occurs. There is an entire class for handling such issues known as the IOException class, which falls under the Java.io package. Reasons Occurring IOExceptionSome common reasons why IOException takes place are:
Example:Java
Output: Exception in thread "main" java.io.FileNotFoundException: file.txt (No such file or directory) How to Handle IOException?IOExceptions can be handled explicitly using try-catch and finally blocks. The code that may contain an exception must be written inside the try block; code handling exceptions should be written inside the catch block; and finally, the block contains the piece of code that must be executed irrespective of the occurrence of any issue. Note that use of final block is not a must, It must be used as per the requirement, while try-catch block are must. There can be one try block having multiple catch blocks as well. Now, let us discuss the syntax for using these blocks. Syntax: IOException can be handelled using try-catch and finally blocks. The basic syntax for using these blocks is: try{ Example:Java
Output
Error occured: file.txt (No such file or directory) Finally block will always executed, irrespective of occurence of issue Explanation of the above Program:In previous code, when we were trying to open a file which didn’t exist, we got an error that was automatically handled by the IOException class (as we used the throws keyword along with the IOException class). But in this code, we tried to handle the exception explicitly by catching it. The try block contains the same code that we wrote to read a file previously. This time, when an issue occurred, the flow of the programme went inside the catch block, where code could be written to handle that exception. Along with this, using the finally block is not necessary; we can use it as per the requirement. The final block executes always, whether the issue occurs or not. Same, in this code, a file not found exception occurs, then code inside the catch block is executed, and at last, the code present inside the final block is executed. |
Reffered: https://www.geeksforgeeks.org
Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |