exception.getMessage() output with class name - java

I'm trying to fix an issue, in my application I have this code
try {
object1.method1();
} catch(Exception ex) {
JOptionPane.showMessageDialog(nulll, "Error: "+ex.getMessage());
}
and the object1 would do something like that:
public void method1() {
//some code...
throw new RuntimeException("Cannot move file");
}
I get a messsage in my option pane like this:
Error: java.lang.RuntimeException: Cannot move file
but I used getMessage and not toString method, so the name of the class shouldn´t appear, right?
What I am doing wrong?
I already tryied with a lot of exceptions, even Exception itself. I'm looking to solve this no without the need to implement my own Exception subclass
PROBLEM SOLVED - thank you all!
The try and catch were actually being called in get() method from SwingWorker which constructs an ExecutionException with my exception thrown from doInBackground()
I fixed doing this:
#Override
protected void done() {
try {
Object u = (Object) get();
//do whatever u want
} catch(ExecutionException ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getCause().getMessage());
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
}

I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:
public static void main(String[] args) {
try {
throw new RuntimeException("Cannot move file");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
}
...you will see a popup that says exactly what you want.
However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause:
public static void main(String[] args) {
try {
throw new Exception(new RuntimeException("Cannot move file"));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Error: " + getRootCause(ex).getMessage());
}
}
public static Throwable getRootCause(Throwable throwable) {
if (throwable.getCause() != null)
return getRootCause(throwable.getCause());
return throwable;
}
Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.

My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.
Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:
public class Test {
public static void main(String[] args) {
try {
failingMethod();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void failingMethod() {
throw new RuntimeException("Just the message");
}
}
Output:
Error: Just the message

Related

Handle Exception after all lines have been finished execution without finally

I need methodA2 also gets executed even though there is an exception by methodA1(). Here I have added only two methods as methodA1() and methodA2(). Let's say there are many methods. In that case also, the solution should be able to applicable.
class A {
String methodA1() throws ExceptionE {
// do something
}
String methodA2() throws ExceptionE {
// do something
}
}
class C extends A {
String methodC() throws ExceptionE2 {
try {
methodA1();
methodA2();
} catch (ExceptionE e) {
throw new ExceptionE2();
}
}
}
Please note that there can be many methods invoked with methodA1, methodA2. In that case having multiple try, catch, finally will look ugly.. So are there any other methods to do that?
I need to store error information in a log file. In methodA1(), methodA2() ... information in each tag is get validated. what I want is having all the error information in log file. Once exception throws it will generate log file. So I will miss validation information from other tags. So we can't go for finally approach.
You can use a loop with Java 8 lambdas:
interface RunnableE {
void run() throws Exception;
}
class Example {
public static void main(String[] args) {
List<RunnableE> methods = Arrays.asList(
() -> methodA1(),
() -> methodA2(),
() -> methodA3()
);
for (RunnableE method : methods) {
try {
method.run();
} catch (Exception e) {
// log the exception
}
}
}
private static void methodA1() throws Exception {
System.out.println("A1");
}
private static void methodA2() throws Exception {
System.out.println("A2");
}
private static void methodA3() throws Exception {
System.out.println("A3");
}
}
Please note that the interface is needed only when methods throw checked exception. If they were throwing only runtime exceptions, you could use java.lang.Runnable instead.
No other way. If each method can throw exception, but you want to continue execution of remaining methods anyway, then each method call must be in its own try-catch block.
Example:
List<Exception> exceptions = new ArrayList<>();
try {
methodA1();
} catch (Exception e) {
exceptions.add(e);
}
try {
methodA2();
} catch (Exception e) {
exceptions.add(e);
}
try {
methodA3();
} catch (Exception e) {
exceptions.add(e);
}
if (! exceptions.isEmpty()) {
if (exceptions.size() == 1)
throw exceptions.get(0);
throw new CompoundException(exceptions);
}
You will of course have to implement the CompoundException yourself.

Java re-throw Exception

I have a Project with two classes. One Object class and one GUI class.
I would like to throw my own declared Exception if an error occurs.
I have two methods:
public class getValueClass {
private List<Value> liste;
public List<Value> getValues() {
try {
liste = this.getVal();
} catch (ValueException ex) {
System.out.println("EXCEPTION!! " + ex.getMessage());
ex.printStackTrace();
}
return liste;
}
public List<Value> getVal() throws ValueException
{
liste = null;
try {
// initialize list
// do some stuff
//test exception
if(1 == 1)
{
throw new Exception();
}
} catch (Exception ex) {
throw new ValueException("QWE " + ex);
}
return liste;
}
}
Now the exception is thrown and I catch the exception in my getValues Method and print the Message/Stack
But I call the Method getValues in my GUI-Class and I want to catch the Exception there and print some Information in my dialog!
GUI:
public void myMethod()
{
try
{
l = cs.getValues();
}
catch(Exception ex)
{
System.out.println("TEST " + ex.getMessage());
}
}
But I don't get there because I already catch it in the getValues() method.
Is it possible to make it like this WITHOUT adding throws at method declaration for getValues() method? ( I get this method from an interface and will not change it)
You could throw an unchecked RuntimeException such as IllegalArgumentException or customized RuntimeException subclass.
public List<Value> getValues() {
try {
liste = this.getVal();
} catch (ValueException ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
return liste;
}
There is a way to do what you want, but I advise against it depending on your intended purpose of ValueException, as it could be the source of future bugs
You can have ValueException extend RuntimeException. The RuntimeException set of exceptions, as the name implies, are thrown at runtime and are not declared at compile time, and need to be explicitly caught. This way you wouldn't have to add a throws declaration to the getValues() method, but would still catch it in your main method.
Disclaimer explained:
The reason I am not a fan of this idea (and RuntimeExceptions in general) is because they're uncaught until explicitly looked for. This in my mind doesn't make for easy-to-use code, and while it has it's very handy uses, I don't feel right using them because of the uncertainty they carry
Again, this is my opinion, not Java's

how to get the filename of a thrown IOException in java?

I have a try block which handles quite a few file opening/closing/reading/writing (more than one file).
It looks like:
try {
// commands
}
catch (IOException e) {
System.err.println("Error: " + e);
}
The main problem is that e.toString() does not contain information about the filename for which the exception was thrown, if there is an error.
I could check each read/write/open/close operation separately, and then know which file the error happens with, but that seems to defeat the purpose of having the elegant try-catch structure.
Is there any other way out? I just want to be able to print the file name for which e had the error in the try block.
EDIT: Maybe I should make it clear in which scenario this issue arises. This happens when I parse command-line arguments, input/output files, etc. I pass the file names to various functions and methods that can return with an IO error. It seems reasonable to require that I would have a generic way of handling any file problem by printing the error and the filename that had that error. I understand that IOException is more broad than handling IO with files, but surely it makes sense, given that IOException is a specialized exception class, to have a method that returns the IO source for which the error occurred.
You don't - as you know, IOException doesn't have information about the File that generated the exception. It's purpose it too general. If you roll your own, you can capture relevant information and catch your own exception instead.
In the various methods that handle your input, wrap the relevant section in try/catch blocks, catch the IOException, and throw your own with the additional data.
Here is a complete program that demonstrates the basic idea.
class FooException extends Exception {
private static final long serialVersionUID = 2816777468035627105L;
private final String filename;
private final Throwable cause;
public FooException(String filename) {
this(filename, null);
}
public FooException(String filename, Throwable cause) {
this.filename = filename;
this.cause = cause;
}
#Override
public String getMessage() {
return "Error reading file";
}
#Override
public Throwable getCause() {
return cause;
}
public String getFilename() {
return filename;
}
}
public class Soj25375647 {
public static void main(String[] args) {
try {
throwsAnException();
// Do other things that might throw my exception
} catch (FooException e) {
System.err.printf("File: %s, error: %s, caused by %s%n", e.getFilename(), e, e.getCause());
}
}
public static void throwsAnException() throws FooException {
try {
int x = 2 / 0;
} catch (ArithmeticException e) {
throw new FooException("bob.file", e);
}
}
}
Output
File: bob.file, error: soj25375647.FooException: Error reading file, caused by java.lang.ArithmeticException: / by zero
See Also Exception-Handling Antipatterns.
I think I see what's happening here. You probably have something like this:
try {
for (int i = 0; i < something; i++) {
File f = getSomeFile(i);
// Operations that might throw an IOException
}
}
catch (IOException e) {
// handle
}
This is not a good idea; as you say you don't know the file that caused the error. Instead try something like this:
for (int i = 0; i < something; i++) {
File f = getSomeFile(i);
try {
// Operations that might throw an IOException
}
catch (IOException e) {
// handle
break;
}
}
This way, you still have f around when the error is thrown, but it also breaks out of the loop on an error just like the original code. Hope this helps!

Throw, Catch exception mistakes

Im confused how throw and catch work,I understand their are several mistakes with this ExceptionDemo. If someone could fix the mistake and clearly state why and how they corrected it without using all the Java jargon words, and use simple terms
Thank you
public class ExceptionDemo {
public static void main( String [] args ) {
try {
int number = Integer.parseInt(”123”);
if (number > 100) {
catch new ArithmeticException(”Check the number”);
}
}
catch {
System.out.println(”Cannot convert to int”);
}
finally (Exception e) {
System.out.println(”Always print”);
}
}
}
a bit tricky to tell exactly what is needed here. for starters looks like as would need to throw an exception if checking for some sort of valid value. also looks like the catch would need to have the exception handler itself not the finally.
//listing 1 slight re-work original post
public class Main {
public static void main(String[] args) throws ArithmeticException {
try {
int number = Integer.parseInt("123");
if (number > 100) {
// is this what trying to do?
//would expect typically would be used to handle
//something like div by zero, etc.
throw new ArithmeticException("Check the number");
}
}
//catch exception(s) here
catch (Exception e) {
System.out.println("Cannot convert to int:" + e.toString());
}
finally {
System.out.println("Always print");
}
}
}
//listing 2 more typical type thing maybe
public class Main {
public static void main(String[] args) {
try {
//int number = Integer.parseInt("A123"); // if un-comment throws generic exception bad input
int number = 100 / 0; //will throw an "arithmetic" exception
//
if (number > 100) {
//do something.
int x = number++;
}
}
catch (ArithmeticException arithEx){
System.out.println("An ArithmeticException Occurred:" + arithEx.toString());
}
catch (Exception e) {
System.out.println("A general exception occurred:" + e.toString());
}
finally {
//always gets executed. so is good place to clean up, close connections etc.
System.out.println("Always print");
}
}
}
In addition to hurricane's answer, you cannot catch a new exception. Instead you need to throw it.
throw new Exception();

I am trying to create a file via a button press but i keep running into an error

I am creating a checkbook and am unable to create a file to write to for each separate account. When I try to create the file I get the error "unreported exception IOException; must be caught or declared to be thrown". I try to declare that my action listener method throws an exception but that makes the action listener method no longer able to work. I then tried to create a separate method that creates the file and is called by the button press but i still run into the same error
Here is my code:
public void actionPerformed(ActionEvent e) {
...
if (e.getSource() == create) {
creatNewAccount(name3.getText());
BALANCE = Double.parseDouble(name2.getText());
}
}
public void creatNewAccount(String s) throws IOException {
FileWriter fw = new FileWriter(s + ".txt", false);
}
creatNewAccount is declared as possibly throwing an IOException. IOException is not a RuntimeException, so you must catch it.
if (e.getSource() == create) {
try {
creatNewAccount(name3.getText());
} catch (IOException ie) {
ie.printStackTrace();
// handle error
}
BALANCE = Double.parseDouble(name2.getText());
}
For more information, please read about The Catch or Specify Requirement and Catching and Handling Exceptions.
A few other things I noticed:
- The word you're looking for is create, not creat.
- You're assigning something to BALANCE. Uppercase names are generally reserved for constants. Consider renaming this variable balance.
- Consider more descriptive names for your text fields. name2 and name3 don't really say much.
IOException is a checked exception. Given that you're calling it within an ActionListener, rethrowing the exception is not an option so you need to catch it.
try {
creatNewAccount(name3.getText());
} catch (IOException e) {
e.printStackTrace();
// more exception handling
}
In your actionPerformed() you need to put a try/catch block around the createNewAccount call. What you do with the exception once caught is up to you -- an easy thing to do is to wrap it in a RuntimeException which does not need to be caught (but might foul up your process until you do something more elaborate).
public void actionPerformed(ActionEvent e) {
...
if (e.getSource() == create) {
try {
creatNewAccount(name3.getText());
} catch( IOException ioe) {
System.err.println("Whoops! " + ioe.getMessage());
throw new RuntimeException("Unexpected exception", ioe);
}
BALANCE = Double.parseDouble(name2.getText());
}
}
It's likely you'll just need to catch the exception inside the method:
public void creatNewAccount(String s) {
try{
FileWriter fw = new FileWriter(s + ".txt", false);
} catch (IOException e){
//TODO something to handle the error
}
}

Categories

Resources