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

Eston Burciaga
Eston Burciaga
1,729 Points

in the Android Data Persistence lab, why is "catch (Exception e)" not catching all errors?

I am trying to solve one of the code challenges in the "Android Data Persistence" track and in one of the code challenges, I am asked to catch the generic Exception. I am using "catch (Exception e)" to catch the generic exception, but the errors come back saying that specific exceptions to a call made are not being caught. I thought that catching the generic exception "Exception" caught all errors. Am I wrong about that?

CodeChallenge.java
// assetManager, assetName, and fileToWrite have been initialized elsewhere

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

2 Answers

Dan Johnson
Dan Johnson
40,533 Points

Catching Exception will catch all of its subclasses, however you need to put the code dealing with assignment/instantiation in the try block as well. The FileOutputStream constructor can throw FileNotFoundException for example.

Eston Burciaga
Eston Burciaga
1,729 Points

Thanks, Dan. I realized that I didn't have the try/catch block around all of the code that could throw exceptions. I extended the try/catch block around the entire block of code that could possibly throw an exception and that fixed the problem.

Thanks for your help!