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 trial

Android Android Data Persistence Introduction to Data Persistence Handling an Exception

Exception 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?

CodeChallenge.java
// 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

Hi 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.

I 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?

Yes, in that example name is an instance of Exception. There are many types of exception, all being subclasses of the generic catch-all Exception class. So, you'll see IllegalArgumentException and NullPointerException and any number of others. You can catch each type separately if you want so you handle each one in a different way. There's a list of them here.