Calling a method which throws exception - java

I have this method that throws exception
public String Pipeit() throws TransformerException,
TransformerConfigurationException,SAXException, IOException
i tried calling this method from a GUI
Pipe P = new Pipe (fname,x1name,x2name,x3name,oname);
view.setText(P.Pipeit()throws TransformerConfigurationException,SAXException,
IOException))
It kept giving this error
')' is expected.

throws TransformerConfigurationException,SAXException, IOException
should only be specified when you declare the method, not when you call it.
Also, variable names should by convention begin with a lower-case letter, and as #ssloan points out, method names should be in lower camelCase.
Change your code to
Pipe p = new Pipe (fname,x1name,x2name,x3name,oname);
view.setText(p.pipeIt());

Here's one way to write this with correct syntax:
Pipe P = new Pipe (fname,x1name,x2name,x3name,oname);
try {
view.setText(P.Pipeit());
} catch (TransformerConfigurationException e) {
//log/handle the exception
} catch (TransformerException e) {
//log/handle the exception
} catch (SAXException e) {
//log/handle the exception
} catch (IOException e) {
//log/handle the exception
}

While invoking method, you don't need to include entire method signature ( in this case throws clause).
view.setText(P.Pipeit()throws TransformerConfigurationException,SAXException,
IOException))
should be
view.setText(new P().Pipeit())

Related

Same exception type with different error message

Ive two method that throw the same exception throws IOException
the problem is that each method throw it from different reason, I wrap the methods
in the main with try catch, what is the recommended way to solve it ?
I need different message for each exception with the same type..
public static void main(String[] args) {
try{
….
readFile(path);
convert(file)
} catch (IOException e) {
…..
}
private static String readFile(String path) throws IOException {
//Here files requires IOException - Reason here cannot Read file
String lineSeparator = System.getProperty("line.separator");
List<String> lines = Files.readAllLines(Paths.get(path));
}
private static String convert(String file) throws IOException {
//Here reader requires also ioException- Reason here cannot parse file
ObjectMapper reader = new ObjectMapper(new YAMLFactory());
Object obj = reader.readValue(file, Object.class);
}
There are several ways you could approach this. One way, perhaps the heaviest in terms of new code you would need to write, would be throw a custom exception from each of your helper methods. Then you could catch each specific exception in a separate block.
But what I might recommend here is that you simply wrap each of the two calls to your helper methods in separate try-catch blocks:
try {
readFile(path);
} catch (IOException e) {
// handle first exception here
}
// more code
try {
convert(file)
} catch (IOException e) {
// handle second exception here
}
This is fairly clean and doesn't require a lot of refactoring. If you keep encountering this problem, then maybe consider creating custom exceptions for your application. If you have a look at many Java libraries, you will see that they often use their own custom exceptions.
If you wanted to go the route of using a custom exception, you could define one, e.g.
public class FileReadIOException extends Exception {
public FileReadIOException(String message) {
super(message);
}
}
and then use it:
private static String readFile(String path) throws FileReadIOException {
try {
String lineSeparator = System.getProperty("line.separator");
List<String> lines = Files.readAllLines(Paths.get(path));
}
catch (Exception e) {
throw new FileReadIOException(e.getMessage());
}
}
try {
readFile(path);
// more code
convert(file)
} catch (FileReadIOException e) {
// handle first exception here
} catch (SomeOtherException e) {
// handle second exception here
}
The above code showing custom exception is a bit contrived, because the reality is that all of your code is throwing IOException. Creating custom exceptions in your case does not add much value, because they are already (rightfully) throwing an IOException. I'm not sure that it doesn't make sense to handle just one type of exception. More typically, if you were working on a large enterprise application, you would use custom exceptions to handle situations which go wrong in your own custom code.
My way is usually to create your own exception and throw it like that
public class Snippet {
public static void main(String[] args) {
try {
String path = "";
readFile(path);
String file = "";
convert(file);
} catch (MyException e) {
// do whatever
}
}
private static String readFile(String path) throws MyException {
try {
String lineSeparator = System.getProperty("line.separator");
List<String> lines = Files.readAllLines(Paths.get(path));
} catch (Exception e) {
throw new MyException("Custom 'readFile' message", e);
}
}
private static String convert(String file) throws MyException {
try {
ObjectMapper reader = new ObjectMapper(new YAMLFactory());
Object obj = reader.readValue(file, Object.class);
} catch (Exception e) {
throw new MyException("Custom 'convert' message", e);
}
}
}
class MyException extends Exception {
private static final long serialVersionUID = -3166824380774329449L;
public MyException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
}
Tim's way is valid too.
#OP The best person to solve this would be you yourself.
There are quite easily multiple ways to solve that. Check which one suits you more properly.
One of the solution as per me is below. This is based on the reason IOException is superclass to many other exceptions. IOException documentation
try {
readFile(path);
} catch ( FileNotFoundException e) {
// handle first exception here
} catch ( EOFException e) {
// handle 2nd exception here
}
For the above to work you would need to know which type of IOException is being thrown.
Another solution is check individual exception messages when you know what are expected messages you may receive.
try {
readFile(path);
} catch ( IOException e) {
if(e. getMessage().contains("TXT 1...") {
//Case handle #1
} else if(e. getMessage().contains("TXT 2...") {
//Case handle #2
}
}
The best way to handle exception is not to have them. When exception is thrown, it indicates that natural lifecycle of your application has been interrupted for one reason or another. Most exceptions are self-explanatory and provide you with precise explanation of what happend, therefore creating new exceptions and re-mapping those thrown is almost always counterproductive and may result in more confusion than usefulness(especial if you work in a team).
Furthermore exceptions doesn't need to be terminal, in most cases, a scenario can be devised to retry/prompt different input etc. to ensure that lifecycle is not interrupted. Killing an application on exception can create more problems in some cases (e.g: not closing files properly, hence losing processed data).
Now to your actual problem. If you have two or more components, that throws unrelated exceptions(name is not a relation in this case), it is best not to have them in the same try/catch structure as less workaround will be necesary to scrap that one part, instead of the whole thing which can still exit on its own, or doesn't even need to be initiated.
Here is my 5 cents
public static void main(String[] args) throws Exception {
String path = "path";
String path2 = "path2";
try{
readFile(path);
} catch (IOException e) {
throw new Exception("read file exception", e);
}
try{
convert(path2);
} catch (IOException e) {
throw new Exception("convert exception", e);
}
}
private static String readFile(String path) throws IOException {
//Here files requires IOException - Reason here cannot Read file
String lineSeparator = System.getProperty("line.separator");
List<String> lines = Files.readAllLines(Paths.get(path));
}
private static String convert(String file) throws IOException {
//Here reader requires also ioException- Reason here cannot parse file
ObjectMapper reader = new ObjectMapper(new YAMLFactory());
Object obj = reader.readValue(file, Object.class);
}

Java compiler complaining about unreported IOException

I'm trying to write a method that lists all non-hidden files in a directory. However, when I add the condition !Files.isHidden(filePath) my code won't compile, and the compiler returns the following error:
java.lang.RuntimeException: Uncompilable source code - unreported exception
java.io.IOException; must be caught or declared to be thrown
I tried to catch the IOException, but the compiler still refuses to compile my code. Is there something glaringly obvious that I'm missing? Code is listed below.
try {
Files.walk(Paths.get(root)).forEach(filePath -> {
if (Files.isRegularFile(filePath) && !Files.isHidden(filePath)) {
System.out.println(filePath);
} });
} catch(IOException ex) {
ex.printStackTrace();
} catch(Exception ex) {
ex.printStackTrace();
}
The lambda expression passed to Iterable#forEach isn't allowed to throw an exception, so you need to handle it there:
Files.walk(Paths.get(root)).forEach(filePath -> {
try {
if (Files.isRegularFile(filePath) && !Files.isHidden(filePath)) {
System.out.println(filePath);
}
} catch (IOException e) {
e.printStackTrace(); // Or something more intelligent
}
});
isHiddenFile() throws an IOException, and you're not catching it. Indeed, forEach() takes a Consumer as argument, and Consumer.accept() can't throw any checked exception. So you need to catch the exception inside by the lambda expression passed to forEach():
Files.walk(Paths.get(root)).forEach(filePath -> {
try {
if (Files.isRegularFile(filePath) && !Files.isHidden(filePath)) {
System.out.println(filePath);
}
}
catch (IOException e) {
// do something here
}
});

How to handle multiple exceptions in a java method?

I've read It isn't a best practice to handle multiple Exceptions like this:
public void myMethod() throws ExceptionA, ExceptionB, ExceptionC {
//more code here
}
And then to call myMethod():
try {
myObject.myMethod();
} catch(Exception e) {
//More code here
}
Despite Exception is the parent class of all the other exceptions, it is consider a bad practice. But, in my application I'm using java SE 6 and I need to:
Do File operations that can imply a FileNotFOundException and IOException
Marshal objects (in order to create XML files) JAXBException
Create a pdf file (using pdfbox library) COSVisitorException
Send an email using JavaMail, MessagingException
The easiest way is to add a throws statement in method declaration, but what could be the proper way to write the client method?
Is it OK to add 6 or 7 catch blocks to handle all the possible exceptions?
Generally speaking (for Java 6 and below), you should handle each exception individually...
try {
myObject.myMethod();
} catch (ExceptionA e) {
// Condition for A
} catch (ExceptionB e) {
// Condition for B
} catch (ExceptionC e) {
// Condition for C
}
This allows you to handle each exception differently based on what it is, but also means you are only handling those exceptions reported to be thrown by the method
In Java 7+ you can make use of "multi-catch" or "combined catch" (we can't find an "official" term)
try {
myObject.myMethod();
} catch (ExceptionA | ExceptionB | ExceptionC e) {
// Condition for A and B and C
}
But even then, you should be focusing exceptions into "common" use groups
try {
myObject.myMethod();
} catch (ExceptionA | ExceptionB e) {
// Condition for A and B
} catch (ExceptionC e) {
// Condition for C
}
Another option, if you control how the exceptions are defined, is to extend from a common base exception, a good example of this is the FileNotFoundException which extends from the IOException, which is thrown by FileReader and FileInputStream (as examples), this means you can handle the FileNotFoundException as a common IOException should you wish...
FileReader fr = null;
try {
fr = new FileReader(new File(...));
// Read from reader...
} catch (IOException exp) {
// Common catch block
} finally {
// Best attempt to close
try {
fr.close();
} catch (Exception exp) {
}
}
Or you could handle the FileNotFoundException as it's own condition...
FileReader fr = null;
try {
fr = new FileReader(new File(...));
// Read from reader...
} catch (FileNotFoundException exp) {
// File not found condition
} catch (IOException exp) {
// Other IO condition
} finally {
// Best attempt to close
try {
if (fr != null) {
fr.close();
}
} catch (Exception exp) {
}
}
This allows you to either group "like" exceptions together, but also provides you with the control to define more fine grained conditions should you need to...
Beware though, we the above example, if I put the IOException first, the FileNotFoundException would never be handled, when doing this, make sure that you use the lowest/tightest/finest exceptions first, as they are processed sequentially in the order you have listed
Another option (which I'm not keen on, but have seen) might be to catch a "common" ancestor and then compare the actual type, which would allow you to provide common handlers for some sub-type of the exception.
} catch (IOException exp) {
if (exp instanceof FileNotFound || exp instanceof FileSystemException) {
// Common handling
} else {
// Generic handling
}
}
This might be helpful in situations where the method only throws the ancestor type (ie IOException), but you need to provide a more fine grained resolution
But, again, I would be focused on only handling the expected "common" exceptions declared as been thrown, don't be tempered to catch Throwable for example

Difference between catching exceptions using Exception class or FileNotFoundException class

Like i have these two scenarios where we have to handle FileNotFoundException
Case1:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Case2:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (Exception e) {
e.printStackTrace();
}
In both cases printed Stack Trace is same. I would like to know the difference between both implementations and what should be preferred ?
From the docs it gives the reason:
"A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they
are not inherited by subclasses, but the constructor of the superclass
can be invoked from the subclass."
Exception class is the parent of all the other exception class. So if you know that you are going to get the FileNotFoundException then it is good to use that exception. Making the Exception is a generic call.
This would help you understand:
So as you can see that the Exception class is at a higher hierarchy, so it means it would catch any exception other than the FileIOExcetion. But if you want to make sure that an attempt to open the file denoted by a specified pathname has failed then you have to use the FileIOExcetion.
So here is what an ideal approach should be:
try {
// Lets say you want to open a file from its file name.
} catch (FileNotFoundException e) {
// here you can indicate that the user specified a file which doesn't exist.
// May be you can try to reopen file selection dialog box.
} catch (IOException e) {
// Here you can indicate that the file cannot be opened.
}
while the corresponding:
try {
// Lets say you want to open a file from its file name.
} catch (Exception e) {
// indicate that something was wrong
// display the exception's "reason" string.
}
Also do check this: Is it really that bad to catch a general exception?
In case 2, the catch block will be run for all Exceptions that are caught, irrespective of what exception they are. This allows for handling all exceptions in the same way, such as displaying the same message for all types of exceptions.
In case 1, the catch block will be run for FileNotFoundExceptions only. Catching specific exceptions in different catch blocks allows for the handling of different exceptions in different ways, such as displaying a different message to the user.
When an exception occures the JVM throws the instance of the Exception and that instance is passed to the respective catch block , so in catch(Exception e) e is just the reference variable , but the instance it points to is of Exception thrown .
In case of catch(FileNotFoundException e) , e is also a reference variable and the instance it points to is of Exception thrown , so in both cases different reference varibales (i.e. e) are pointing to the instance of same the Exception (which is thrown) .
this is what i prefer :
try {
// some task
} catch (Exception e) {
if (e instanceof FileNotFoundException) {
// do this
}
if (e instanceof NullPointerException) {
// do this
} else {
// do this
}
}
It is a matter of what you want to intercept. With Exception you will catch any exception but with FileNotFoundException you will catch only that error case, allowing the caller to catch and apply any processing.
When you write this:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
The code inside the catch block is only executed if the exception (thrown inside the try block) is of type FileNotFoundException (or a subtype).
When you write this, on the other hand:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (Exception e) {
e.printStackTrace();
}
the catch block is executed for any exception (since Exception is the root type of any exception).
If your file (test1.txt) does not exist, a FileNotFoundException is thrown and both code snippets are able to catch it.
Try and change it to something like:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (NullPointerException e) {
e.printStackTrace();
}
and you will see that the catch block is no longer executed.
Exception class is the parent of FileNotFoundException.
If you have have provided the Exception in the catch statement, every Exception will be handled in the catch block. But if FileNotFoundException is present in catch block, only exceptions rising due to absence of a File at said source or permissions not available to read the file or any such issues which makes spoils Java's effort to read the file will be handled. All other exceptions will escape and move up the stack.
In the code snippet provided by you, it is fine to use both. But i would recommend FileNotFoundException as it points to exact issue in the code.
For more detail you can read Go Here
Don't use any of those.
Don't catch Exception. Why? Because it also catches all unchecked exceptions (ie, RuntimeExceptions and derivates). Those should be rethrown.
Don't use the old file API. Why? Because its exceptions are unreliable (FileNotFoundException can be thrown if you try and open a file to which you have no read access to for instance).
Use that:
final Path path = Paths.get("test1.txt");
try (
final InputStream in = Files.newInputStream(path);
) {
// do something with "in"
} catch (FileSystemException e) {
// fs level error: no permissions, is a directory etc
} catch (IOException e) {
// I/O error
}
You do need to catch FileSystemException before IOException since the former is a subclass of the latter. Among other possible exceptions you can have: AccessDeniedException, FileSystemLoopException, NoSuchFileException etc.

In Java, if a general exception is caught and rethrown, will outer methods still be able to catch specific exceptions?

In Java, if a general exception is caught and rethrown, will outer methods still be able to catch specific exceptions?
In other words, can I do this:
try {
try {
//...
} catch (Exception e) {
//...
throw e;
}
} catch (SpecificException e) {
//...
}
re-throwing an exception does not change anything about it (it's still the same object originally thrown).
While jtahlborn answer is correct, there is one more appreciation: the compiler will see that you are throwing an exception of the generic type (even if at runtime it can be only of the specific class) and will force you to declare the generic exception in the method header.
private void test() throws FileNotFoundException {
try {
throw new FileNotFoundException("Es una exception");
} catch (IOException e) {
throw e; <-- Error because the method only throws
FileNotFoundException, not IOException
}
}
e is indeed FileNotFoundException, but as it is declared as IOException the compiler works with the broader class. What you can do is "cast" the exception.
throw (FileNotFoundException) e;
Eclipse marks the "throw e" in the inner catch as an unhandled exception, BUT it does catch the exception because when I run this it prints "It worked!". Thanks #jtahlborn. Unfortunately this means that there will still need to be an unnecessary try/catch block somewhere.
public class Tester {
public static void main(String[] args) {
try {
try {
throw new SpecificException("Test!");
} catch (Exception e) {
throw e;
}
} catch (SpecificException e) {
System.out.println("It worked!");
}
}
}

Categories