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:
- Why am I getting the first and not the second?
- How can I update my code to catch the
incompatible typeserror?