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

yossi nagar
yossi nagar
2,652 Points

pls explain me try and catch

Handling an Exception

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 e) {

1 Answer

Hi Yossi,

You're prety much there with your code - there's only one last bit to finish off.

Inside the try block, you put the code that you know can throw exceptions. Often this is file IO operations, code requiring network access etc. Things where external factors can cause it not to function as you intend. So, the code is tried - if it work, cool - away your app goes working as you want it to. If it fails, though, you then catch the exception. There are different sorts of exceptions, in this challenge, we're dealing with a basic catch-all Exception which is the general superclass, I guess.

Inside the catch, you can manage the exception. There's lots of ways to do this - it could be utilising default settings to bypass the requirements of the code that failed, or it could just be logging the problem, as in this example. The exception is used as a parameter, passed into the catch block as an instance of its Exception type.

Here we just want to use printStackTrace() to output the issue:

try {
  InputStream in = assetManager.open(assetName);
  FileOutputStream out = new FileOutputStream(fileToWrite);
  copyFile(in, out);
} catch (Exception e){
  e.printStackTrace();  
}

I hope that helps.

Steve.