1

Consider this:

public class Minesweeper extends MIDlet implements CommandListener {
  public static String error = "";

  public void startApp() throws MIDletStateChangeException {

    try{
        int int = 5;
    } catch (Exception e) {
        error = e.toString();
    }
  }
}

int is an invalid name for an int, so surely the error should be caught and registered in error? (This error is there on purpose so I can catch it)

You've probably guessed it though, the error doesn't seem to be caught, and the app stops with a java/lang/Error Unresolved compilation problem: syntax error on token 'int'....

What am I doing wrong.

(BTW, this was just a test so I knew I could catch errors properly, I'm obviously not going to use that code in a final version.)

ACarter
  • 5,688
  • 9
  • 39
  • 56

2 Answers2

2

Here is your problem - "int int = 5;" - you cannot use "int" as a variable name ;)

You are trying to use a reserved word as a variable name. The compilation problem has nothing to do with your try-catch block working or not working, the compiler never gets that far.

Xelloss
  • 71
  • 2
  • So you can't catch errors like that? Which errors can you catch? – ACarter Oct 20 '12 at 10:10
  • 3
    Well, in the context of this problem - I would say the easiest way to explain it is try/catch works when the *program* tries to do something, and it fails. However to get a program to compile, you have to follow the proper rules/syntax for the language/compiler. In other words, try/catch is more for catching *runtime* exceptions - not compile time errors. – Xelloss Oct 20 '12 at 12:52
1

Try/catch blocks can't be used for that kind of error.

If you try loading a file that isn't there, then it'll trigger. Try this:

  Image img = Image.createImage("blabla.png");
mr_lou
  • 1,910
  • 2
  • 14
  • 26