Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMalcolm Mutambanengwe
4,205 PointsException printStackTrace()
Hi Steve Hunter . Its exception time! I don't know if i've understood the code. I am supposed to wrap the code up and catch an exception. So i said : try { code} catch (exception) {printStackTrace(exception) }. Your awesomeness is appreciated. Why haven't I seen these exceptions in many codes before? Are they only used for data persistence?
// assetManager, assetName, and fileToWrite have been initialized elsewhere
try {
InputStream in = assetManager.open(assetName);
FileOutputStream out = new FileOutputStream(fileToWrite);
copyFile(in, out);
} catch (Exception) {
cause.printStrackTrace(Exception);
}
1 Answer
Steve Hunter
57,712 PointsHi Mal,
You've got that so nearly correct. You just need to create a parameter of type Exception
in the catch
block parentheses. I called mine e
and then used dot notation to call printStackTrace()
on it:
try{
InputStream in = assetManager.open(assetName);
FileOutputStream out = new FileOutputStream(fileToWrite);
copyFile(in, out);
} catch(Exception e) {
e.printStackTrace();
}
Make sense?
This type of exception management is common - you'll see it a lot.
Steve.
Malcolm Mutambanengwe
4,205 PointsMalcolm Mutambanengwe
4,205 PointsI get it, many thanks
try{ InputStream in = assetManager.open(assetName); FileOutputStream out = new FileOutputStream(fileToWrite); copyFile(in, out);
} catch(Exception name) { name.printStackTrace(); }
So name is the "name" of the exception?
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsYes, in that example
name
is an instance ofException
. There are many types of exception, all being subclasses of the generic catch-allException
class. So, you'll seeIllegalArgumentException
andNullPointerException
and any number of others. You cancatch
each type separately if you want so you handle each one in a different way. There's a list of them here.