Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,532 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!