Why can't I throw or snatch instances of a generic class in java?

I know that I cannot throw or catch instances of a generic class in Java, for example, the following code does not compile correctly:

public static <T extends Throwable> void test(Class<T> t){ try{ //do work } catch (T e){// ERROR--can't catch type variable Logger.global.info(...) } } 

Can anyone explain why it was Java that forbade throwing or grabbing instances of the generic class?

+5
source share
2 answers

You cannot catch a general exception because the Java language specification explicitly forbids it. At 14.20, the try statement says:

This is a compile-time error if a type variable is used in the type designation of the exception parameter.

The section does not explain why, but the most likely reason is that <T extends Throwable> is erased to Throwable , so your code will be compiled as if it were:

 public static void test(Class<? extends Throwable> t){ try{ //do work } catch (Throwable e){ Logger.global.info(...) } } 

This is not the intention expressed by your code (and most likely not what you want), so the language specification explicitly forbids it.

Note that the exception of general exceptions is allowed, but this usually only makes sense in the context of having some kind of wrapper around another method that throws an exception.

+3
source

You cannot do this because "erasing a type is a general type." General information is lost after compilation time, after generating the bytecode class file, there is no general information, and during compilation you did not specify a specific type for general T.

See this code to check for type erasure, the result is:

A

 package a; public class A { public static void main(String[] args) { final B<String, Integer> b = new B<String, Integer>(); b.check(); } } 

IN

 package a; import java.util.ArrayList; import java.util.List; public class B<T, E> { public void check(){ final List<T> listT = new ArrayList<T>(); final List<E> listE = new ArrayList<E>(); if (listT.getClass().equals(listE.getClass())) { System.out.println("Equal"); } } } 

See also this link: http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#cannotCatch

+1
source

Source: https://habr.com/ru/post/1235945/


All Articles