FileNotFoundException in JavaFileNotFoundException is another exception class available in the java.io package. The exception occurs when we try to access that file which is not available in the system. It is a checked exception because it occurs at run time, not compile-time, and it is thrown by one of the following constructors:
FileNotFoundException ConstructorFileNotFoundException class has the following two constructors: 1. FileNotFoundException()It constructs a FileNotFoundException and set the error detail message null because we didn't pass any parameter to the constructor. Syntax: The syntax of the FileNotFoundException is as follows: 2. FileNotFoundException(String str)It constructs a FileNotFoundException and set the error detail message str, which we pass to the constructor. Syntax: The syntax of the FileNotFoundException is as follows: FileNotFoundException MethodsIt provides all the methods that are provided by the java.lang.Throwable and the java.lang.Object classes because it is a subclass of both these classes. Methods of java.lang.Throwable classaddSuppressed(), fillInStackTrace(), getCause(), getLocalizedMessage(), getMessage(), getStackTrace(), getSuppressed(), initCause(), printStackTrace(), printStackTrace(), printStackTrace(), setStackTrace(), and toString(). Methods of java.lang.Object classclone(), equals(), finalize(), getClass(), hashCode(), notify(), notifyAll(), and wait(). To learn more about these methods, visit the following: https://www.javatpoint.com/object-class https://www.javatpoint.com/post/java-throwable Why FileNotFoundException occurs?There are mainly two reasons by which we get this error. The reasons for getting this exception are as follows:
Let's takes some examples and understand both the above points one by one: FileNotFoundExample1.java Output: FileNotFoundExample2.java Output: Handling FileNotFoundExceptionIn order to handle the exception, it is required to use the try-catch block. In the try block, we will put that line of code that can throw an exception. Whenever an exception occurs, the catch block will handle it. There are some other ways through which we can remove the FileNotFountException and which are as follows:
So, in the FileNotFoundExceptionExample1 class, we put the FileReader code in the try-catch block and ensure that the given filename is available in the directory. FileNotFoundExample1.java Output: Next TopicInputMismatchException in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India