1
votes

I was fiddling around with try ... catch statements in Java, and I came across an unexpected result.

When I run this code:

public class Test 
{
    public static void main(String[] args)
    {
        int res = 418;
        try {
            res = "foobar";
        }
        catch (Exception e) {
            System.out.println("Uh oh!");
        }
        System.out.println(res);
    }
}

I get this error in the console:

Test.java:7: error: incompatible types: String cannot be converted to int
            res = "foobar";
                  ^
1 error

Since the (purposefully) problematic code is in a try block, I would expect this output:

Uh oh!
418

I have two questions:

  1. Why am I getting the first and not the second?
  2. How can I update my code to catch the incompatible types error?
The title needs work. - Basil Bourque
try catch exceptions during time time. your problem is just compilation error. It has nothing to do with exception handling. - Cheng Thao
That's compiler Error (Syntax) not an Exception (Error/ checked / RunTimeException) - adam
Yep, time to review the difference between a compilation error and a run-time exception. You're trying to equate apples with oranges and this suggests a fundamental misunderstanding of these concepts. Please check out Java - When is it a compiler error and when is it a runtime exception?. Also check out these related on-site links - Hovercraft Full Of Eels
@BasilBourque — thank you, I must have been working a bit too fast. Thank you to everyone else for the info! I'm used to working with JavaS͟c͟r͟i͟p͟t, which isn't statically typed, so I didn't think about that when I was considering the error. - Ben Z.