import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Filewrite {
public static void main(String args[]) {
try{
String content="This is my world";
File f=new File("D:/abc.txt");
}catch(IOException i) {
i.printStackTrace();
}
}
}
Compilation of the above code gives an error:
IO exception is never thrown by this corresponding try block.
What exception may be thrown while creating a file?
From Java Docs:
Throws:
NullPointerException - If the pathname argument is null
When you want to see what Exceptions are being thrown by a method (constructor in this case), you can search in Java Docs, or if you are using Eclipse IDE, put cursor over the method, and press F2.
IOException comes when
Signals that an I/O exception of some sort has occurred. This class is
the general class of exceptions produced by failed or interrupted I/O
operations.
in your code you are just creating a file object. It throws a NullPointerException if the path is null.
If you want to do any operations with that file like read, write etc... it throws FileNotFoundException and IOException
The error caused because your code block will never throw an IOException.
IOException will be thrown mostly when doing IO operations on files or other sources
Explanation
When ever you try to catch checked exception only which will never be thrown by your code in try block then compiler will always give you error of compilation.
In this case you are not performing any file operation(creation, reading, writing).
So your code will never throw any io exception which is checked exception.
You can't catch that exception which will never be thrown by your try block.
How To Fix
You can fix by removing io-exception from catch block then code will compile fine.
Related
This question already has an answer here:
Unreported exception java
(1 answer)
Closed 2 years ago.
I have some trouble finding the file in a java program in mac system.
import java.io.File;
import java.util.Scanner;
import java.net.MalformedURLException;
import java.net.URL;
public class Data{
public static void main(String[] args){
File file = new File("/Users/project/test.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
In the same directory, when I typed this command Javac Data.java, it would give this error
I have read multiple similar posts on StackOverflow, but unfortunately, I couldn't find a solution.
Data.java:9: error: unreported exception FileNotFoundException; must be caught or declared to be thrown Scanner sc = new Scanner(file);
^
1 error
I have tried setting the file path like:
"./test.txt"
"test.txt"
"/text.txt"
But still, the same error would occur.
I don't know if this is relevant, but I can only run the java command in the terminal in the ~ directory, and all the above java files are in the ~ directory too.
Does anyone have any suggestions?
Your code is not throwing an exception. Your error message does not mean that the FileNotFoundException is thrown.
You have a compile time error.
Whenever you open a file, it must be like this:
try {
File file = new File("/Users/tianrongzhen/project/test.txt");
} catch (Exception e) {
// handle exception here
}
Or like this:
public static void main(String[] args) throws FileNotFoundException {
File file = new File("/Users/tianrongzhen/project/test.txt");
// rest of your code
}
There are 2 kinds of exceptions: Checked and Unchecked.
A Checked exception can be considered one that is found by the compiler, and the compiler knows that it has a chance to occur, so you need to catch or throw it.
For example, opening a file. It has a chance to fail, and the compiler knows this, so you're forced to catch or throw the possible IOException or FileNotFoundException.
There is a huge difference between the two ways to handle exceptions above.
First one catches and handles Exception internally, so the caller doesn't have to do any exception handling.
Second one throws Exception, so the caller needs to handle the Exception.
Based on the question you have asked here, I would recommend you to read up on the basics on exception handling. Here is one resource, but feel free to explore.
I know questions like this are everywhere, but I read a lot of things about this, and I still can't understand what the "throws" command do. I will be more specific now:
So, one of the examples I saw was this one, with the following code:
public class CatchThrow {
private static void throwsMethod() throws NumberFormatException {
String intNumber = "5A";
Integer.parseInt(intNumber);
}
private static void catchMethod() {
try {
throwsMethod();
} catch (NumberFormatException e) {
System.out.println("Convertion Error");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
catchMethod();
}
}
Now, if I remove the "throws NumberFormatException" from the "throwsMethod" method, the program will run the same, and will give the same results. Actually, every example with the throws command that I saw did the same, so I can't really understand why use it.
I'm using the Eclipse IDE, version 4.7.2.
Normally your function exits at the end of the function or the return statement.
However, a function can also exit when it reaches a throw statement. If the exception subclasses Exception, the caller of the function must surround the function call with a try { } catch { } block. If the exception subclasses RuntimeException you may optionally surround the function call in a try catch block.
If you look at the JavaDoc for NumberFormatException: https://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html will see it subclasses RuntimeException. This means your try-catch block is optional. The difference between the two program is this: With the try-catch block you will get Convertion Error printed to the console, without it, you will see the full stack trace. This is often called "swallowing the exception".
So basically, if an exception occurs and you don't want to handle that exception there, in that case you use the 'throw' keyword to simply just throw the exception if occurs.
Example: Here, in throwsMethod(), you are not taking care of the Exception Handling i.e. not using the try(), catch() blocks, you are just throwing it if there occurs any Exception. And you will land in catch() block if exception occurs in your throwsMethod().
To get better idea, you should read checked & Unckecked exceptions in Java. For Checked exceptions (happen at compile-time), we use 'throw' keyword and for Unchecked (Run-time), we use try() catch().
Example: NumberFormatException is an Unchecked exception, IOException is a Checked exception.
Read this for reference: https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/
I am new to Java. I was going through the Exception Handling Concept but I stuck at one point here.
We know that whenever the Exception is thrown Java will try to find by looking at the available catch clauses in the top down manner. If it doesn't find one, it will search for a handler for a supertype of the Exception.If it does not find a catch clause that matches a supertype for the exception, then the exception is propagated down the call stack.
Also if most specific exceptions is placed above the more general exceptions handler then it results in the COmpilation error.
Suppose we have a code as shown below:-
try{
// do not know what kind of exception it will be throwing but I am sure that it is IOException
}
try{
// Here the FileNotFoundException is thrown
}
catch(IOException e){
//Do exception handling stuff
}
catch(FileNotFoundException f){
//Do exception handling stuff`
}
Now this code will result in the compilation error because the Supertype of the exception is present above the actual exception.
SO why the first paragraph do not support this concept. i.e After checking JVM will found the appropriate exception(FileNotFoundException) and should not bother about IOException clause, but run into compilation error instead.
Please throw some light on it.
Also let me know If I am able to explain what I want to??
It looks like you are misunderstanding the try concept. You only have one try followed by the catch clauses.
try{
// do not know what kind of exception it will be throwing but I am sure that it is IOException
// Here the FileNotFoundException is thrown
}
catch(IOException e){
//Do exception handling stuff
}
catch(FileNotFoundException f){
//Do exception handling stuff`
}
This code will throw an error at compile time because for FileNotFound Catch Block the code will be unreachable as it's already handled by IO Exception and FileNotFound is subclass for IOException
Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException
FileNotFoundException is a subclass of IOException gives us the choice of either treating all IOExceptions the same, or catch some of IOExceptions subclasses individually
Code snippet has fundamental mistakes
If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it
Recommended reading:
https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
I'm starting to teach myself more about Java error handling, and this is my first program where I'm trying to see specific errors instead of using catch (Exception e) as a generic catch-all catch.
I'm deleting a file and returning a message that the file was deleted successfully or that the deletion was a failure. In cases where the deletion fails, I want to deliver an error message if the file is not found.
Here's where I am so far:
public static void deleteOldConcatFiles(File concatFile) {
try
{
if(concatFile.delete()) {
System.out.println(concatFile.getName() + " is deleted!");
} else {
System.out.println("Delete operation failed.");
}
}
//
catch(FileNotFoundException f) {
System.out.println("Exception: "+ f.getMessage().getClass().getName());
}
}
When I run that, I'm getting a warning: This this is an unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body.
However, when I run with THIS catch block,
catch(Exception f) {
System.out.println("Exception: "+e.getMessage().getClass().getName());
}
I get no error or warning message.
Why is this happening, and what can I do to fix it?
File.delete() does not throw FileNotFoundException, even if the file does not exist.
FileNotFoundException is a checked exception (i.e., not a RuntimeException), so any code that throws it must declare it. Because File.delete() does not declare that it throws FileNotFoundException, the compiler guarantees that it won't, and can promise that your catch block will never be invoked.
The second, catch-all block does not generate a warning because it also catches RuntimeExceptions (RuntimeException extends Exception), which the compiler does not check for you. Thus, it might be invoked, the compiler isn't sure, so it doesn't warn you.
Java supports two kinds of exceptions: checked exceptions (statically checked) and unchecked exceptions (RuntimeException and its subtypes).
The Java compiler can tell at compile time whether a checked exception (such as FileNotFoundException) can be thrown or can definitely not be thrown. It can't tell that for unchecked exceptions (such as IndexOutOfBoundsException). So it will warn about attempts to catch checked exceptions that cannot arise.
If you catch Exception, it will never complain, because RuntimeException is a subtype of Exception, so your attempt will also try to catch exceptions such as IndexOutOfBoundsException.
As others have noted, FileNotFoundException is never thrown by delete. Furthermore it is a checked exception. So the Java compiler will complain.
Because the type of error thrown doesn't match the one you're catching. Try this...
catch(Exception e) {
System.out.println("Exception: "+ e.getClass());
}
That will show you the type of error you should be catching. Obviously this isn't good practice but it's a good exercise for seeing what's happening. Other answers on this page concerning checked and unchecked exceptions are pretty concise.
If you look at the manual here delete() only throws a SecurityException.
Also, it returns a boolean value which indicates whether or not the file was deleted. This should be all the information needed to indicate to the user if everything worked out.
Isnt the message clear? As you dont construct a File object, a FileNotFoundException can never be thrown in this try block. Therefor the compilers informs you that the catch block in unneccessary.
Look for IOException. or deleteifExist method if you are not interested in the exception, if you want to retrn something, then file.exists() will help you fgure if the file is there or not.
I had a strange problem today... I'm going to make a simplified example since it "worth a thousands words" :D
public class Application() {
public static void main(String[] args) {
try {
A a = new A(); // this may throw exceptions
// (which will cause an ExceptionInInitializerError)
} catch (Throwable t) {
JOptionPane.showMessageDialog(null, "Oooops!");
System.exit(1);
}
}
}
Since it's a stand-alone application with a Swing GUI, my goal is to give a message to the user in case of any problems (in this case at startup)... the code above works in Eclipse IDE but when I export the project as executable jar by double-clicking on it, well, it just won't open.
So I try to execute it in cmd with java -jar application.jar and it prints in the shell that there was an ExceptionInInitializerError.
Why the error was not caught?
It doesn't work even if I specify catch (ExceptionInInitializerError e).
EDIT:
After more indepth debugging, I found out that this problem only happens when two particular exceptions occur and the latter occurs in the catch block of the former.
I corrected the bug by changing the order of some checks that I do on startup.
The problem btw should never happen since it was originated by a volountary mistake of the JDBC driver class name to load in a static block.
Well, at least it made me clearly understand why constructors and static initialization blocks should not throw exceptions: it makes debugging almost impossible in the case in which the class that throws the exception is used by many classes, since it may become very hard to find out when the class is loaded.
I can think of three possible explanations for an ExceptionInInitializerError not being caught in your example:
It could be being thrown by JOptionPane.showMessageDialog(null, "Oooops!");
It could be thrown before main is called.
It could be thrown on a different stack.
In fact, I think that the 2nd one is the most likely, as ExceptionInInitializerError is thrown when some unchecked exception is thrown (and not caught) during the initialization of a class. That could well be happening before you enter the try block.