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 trialKyle Spinale
8,507 PointsNot quite sure what the Try and Catch instances are used...
I've watched this video multiple times and I'm a little confused as to what Try and Catch are used for. If someone could help explain this I would greatly appreciate it.
2 Answers
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 PointsVery roughly saying try...catch
block is used to deal with exceptions.
If someMethod throws Exception
, then when you use in other method, you have to use try ... catch
block to deal with exception, or method should re-throw exception
public void someMethod() throws Exception {
// code
}
// you have TO use try catch
public void otherMethod() {
try {
someMethod();
} catch (Exception ex) {
// do stuff
}
}
// or you have-to add throws and catch somewhere else
public void thirdMethod() throws Exception {
someMethod();
}
// in fourth method when we use thirdMethod, we have to catch exception
public void fourthMethod() {
try {
thirdMethod();
} catch (Exception ex) {
// do stuff
}
}
Exceptions is the way Java deals with possible errors in programs. And because all programs have exceptions we use try catch
to deal with exceptions.
Kyle Spinale
8,507 PointsThat makes much more sense. Thank you for clarification!