Search code examples
javauncaught-exception

Java [unchecked] unchecked case warning


Ok, I've been looking around and done alot of google searching, but I still can't find a way to avoid this warning.

Integer result = chooser.showOpenDialog(null);
if (result.equals(0))
{
    String tempHolder = chooser.getSelectedFile().getPath();
    filenameLoad = new File(tempHolder);
    filenameSave = filenameLoad;
    FileInputStream fis = null;
    ObjectInputStream in = null;
    try
    {
        fis = new FileInputStream(filenameLoad);
        in = new ObjectInputStream(fis);;
    }
    catch(IOException ex)
    {
        ex.printStackTrace();
    }

    try
    {
        loadFile = (ArrayList<Dot>)in.readObject();
    }
    catch(IOException ex)
    {
        System.out.println("Cast fail");
    }
    catch(ClassNotFoundException ex)
    {
        System.out.println("Cast fail");
    }
    catch (ClassCastException ex)
    {
        System.out.println("Cast fail");
    }

    try
    {
        in.close();
    }
    catch(Exception ex)
    {
        System.out.println("failed to close in");
    }
    save.setEnabled(true);
      gpanel.setDotList(loadFile);
  }

It gives me the warning at the line loadFile = (ArrayList)in.readObject(); I've added in the catchs so i'm not sure why it still says its uncatched. Any help? thanks?


Solution

  • It is not "uncatched", but "unchecked". The JVM cannot tell at runtime, i.e. when the cast is done, whether the ArrayList really contains Dot elements.

    This warning occurs whenever you cast from a raw type to a generic type. If you are sure the cast is ok, you can suppress the warning with annotation

    @SuppressWarnings("unchecked")
    

    For this, it is good to encapsulate the cast in a small, separate method.