Trying to adapt a try-catch block from a Java tutorial

Can’t make sense of the format in the docs:

try try-expr
catch(varName1:Type1) catch-expr-1
catch(varName2:Type2) catch-expr-2

I’ve seen elsewhere people using a Haxe format similar to Java. I want to make something like this:

//while user is not entering anything usable:
try {
// entry variable was via user input on the command line
var number = Std.parseInt(entry);
} catch(e:Dynamic) {
trace(e + “Please type in a number”);
}

I haven’t even gotten to the loop yet. When compiling, var number creates an unknown identifier error.

If I declare var number = 0, outside of the try block and number= Std.parseInt(entry); inside the try part, the code compiles but the user typing in a non-number causes the program to crash (the try block has no effect).

It’s all normal, Haxe isn’t Java :slight_smile:

  • Std.parseInt isn’t supposed to throw an error but return null for invalid input:
    Std - Haxe 4.2.1 API
  • var number has to be declared outside the try block because variables are locally scoped

If you want to experience an exception you can try:

try {
  var a:Array<String> = null;
  a.push('hello');
} catch (e:Dynamic) {
  trace('oops');
}
1 Like