why this code throws exception?
I have a void method which is part of a flow run by quartz scheduler task.
The content of this method is this code:
try {
InputStream ris = this.getClass().getResourceAsStream("arialuni.ttf");
byte[] ttfAfm = new byte[1];
if (ris != null) {
System.out.println("toByteArray START");
ttfAfm = IOUtils.toByteArray(ris);
System.out.println("toByteArray END");
} else
System.out.println("input stream from arailuni.ttf is null!!!");
ris.close();
ris = null;
bfChinese =
BaseFont.createFont("arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, true, ttfAfm, null);
System.out.println("in myinit() try catch END");
} catch (Exception e) {
System.out.println("exception encountered at myinit() " + e);
}
It's very 开发者_如何学编程strange that this works nice about 30 times (basically, the scheduler scans a directory, take any PCL found and converts it to PDF using this arialuni.ttf font) but suddenly it gives the follwing exception:
19:06:24,316 INFO [STDOUT] toByteArray START
19:06:28,218 ERROR [ReportPollingJob] java.lang.reflect.InvocationTargetExceptio
n
//nothing else here (yes, the exception is only one line...)
at IOUtils.toByteArray(ris)
Can it be because of memory? It's very strange that it does not go to my catch but just throws this exception...
Can you give a hint?
UPDATE: Thanks to mdma: I've changed to catch(Throwable e) and now I see:
java.lang.OutOfMemory: JavaHeap Space
which will not be easy to solve...
The InvocationTargetException
is just a wrapper for the real exception, so you should analyze that (via getCause()
). It is probably an OutOfMemoryError
, which does not subclass Exception
. To catch every error condition, catch Throwable
instead.
This is probably not relevant to the error you are seeing, but it is an error:
If ris is null, you will get a NullPointerException. You have to exit the method after
System.out.println("input stream from arailuni.ttf is null!!!");
or it wil next try to execute
ris.close()
resulting in a NullPointerException.
try {
InputStream ris = this.getClass().getResourceAsStream("arialuni.ttf");
byte[] ttfAfm = new byte[1];
if (ris != null) {
System.out.println("toByteArray START");
ttfAfm = IOUtils.toByteArray(ris);
System.out.println("toByteArray END");
} else
System.out.println("input stream from arailuni.ttf is null!!!");
ris.close(); // it will through NullPointerException in ris is null
ris = null;
bfChinese =
BaseFont.createFont("arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, true, ttfAfm, null);
System.out.println("in myinit() try catch END");
} catch (Exception e) {
System.out.println("exception encountered at myinit() " + e);
}
When working with resource the good practice is like as below
InputStream resource;
try {
resource = createResource();
//use resource object whatever way you want
} catch (Exception e) {
e.printStackTrace();
}
finally {
if(resource != null) {
resource.close();
}
}
Above procedure is true for any kind of resource.
精彩评论