mercredi 26 novembre 2014

Parametrized Method in Java: try-catch does not catch ClassCastException (on Android)


Vote count:

0




Consider creating a new Object and casting it to String within a try-catch block that catches an Exception. Everything seems to be ok. But what does happen if we cast an Object to T within similar try-catch block in a parametrized function? The exception is not catched and the program crashes raising a ClassCastException.



class test
{
Log.i("", String.format("====== CLASS CAST TEST ======"), true);
Log.i("", String.format("====== REGULAR CAST TEST "));
final String test1 = test.regularCastTest(); // the exception thrown is catched within the method
Log.i("", String.format("====== PARAMETRIZED CAST TEST "), true);
final String test2 = test.<String>parametrizedCastTest(); // fails here with ClassCastException without catching it
Log.i("", String.format("------ CLASS CAST TEST END --"), true);

static <T> T parametrizedCastTest()
{
Object obj = new Object();
try
{
final T ret = (T) obj;
Log.d("", String.format("%s; %s", obj.getClass().getSimpleName(), ret.getClass().getSimpleName())); // does not fail and prints 'Object; Object'
return ret;
}
catch (Exception e)
{
e.printStackTrace();
}

return null;
}

static String regularCastTest()
{
Object obj = new Object();
try
{
final String ret = (String) obj;
return ret;
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
}


PS: the parametrized method does not fail if we simply call it without getting the result like:



test.<String>parametrizedCastTest();


asked 2 mins ago







Parametrized Method in Java: try-catch does not catch ClassCastException (on Android)

Aucun commentaire:

Enregistrer un commentaire