try and catch
Description
Put risky code in try and recovery in catch.
Explanation
Catch the most specific exception type you can handle.
Example
try { Integer.parseInt("x"); } catch (NumberFormatException e) { }← Chapter 8 — Exceptions & Collections
mixed
Exceptions represent problems that interrupt normal program flow. Java uses try, catch, finally, and throws to make error handling explicit.
Handle an exception where you can add useful recovery or context. Do not silently ignore a problem; tell the user, log it, or let it reach a layer that can respond.
Put risky code in try and recovery in catch.
Catch the most specific exception type you can handle.
try { Integer.parseInt("x"); } catch (NumberFormatException e) { }finally runs after try/catch; throws declares a possible exception.
Try-with-resources is preferred for closable resources.
void read() throws java.io.IOException { }Checked exceptions must be handled or declared, while unchecked RuntimeException subclasses usually reveal programming or data-validation mistakes. Learn the cause before choosing a response.
public class ExceptionDemo {
public static void main(String[] args) {
try {
int score = Integer.parseInt("ninety");
System.out.println(score);
} catch (NumberFormatException e) {
System.out.println("Please enter a numeric score.");
}
}
}