Explain the use of try, catch, throws and finally with proper example.
Java Exception Handling: try, catch, throws, and finally (With Easy Examples)
In Java, exception handling helps you detect and recover from runtime errors without crashing the program. The main keywords are try, catch, throws, and finally. Understanding them is essential for B.Tech CSE students in the 5th semester, especially when writing robust, error-free code.
What Each Keyword Means
- try: Wraps code that might throw an exception. If an exception occurs inside try, control jumps to the matching catch block.
- catch: Handles a specific type of exception. You can write multiple catch blocks to handle different exceptions.
- throws: Declares that a method might throw exceptions. It does not handle them; it passes them to the caller to handle.
- finally: Runs whether an exception occurs or not. Ideal for cleanup tasks like closing files, database connections, or scanners.
Basic Syntax Patterns
// try-catch
try {
// risky code
} catch (ExceptionType e) {
// handling code
}
// try-catch-finally
try {
// risky code
} catch (ExceptionType e) {
// handling code
} finally {
// cleanup code (always runs)
}
// Method declaration with throws
returnType methodName(...) throws ExceptionType1, ExceptionType2 {
// code that may throw the declared exceptions
}
Example 1: Using try, catch, and finally
This example safely divides two integers input by the user and ensures resources are closed using finally.
import java.util.Scanner;
import java.util.InputMismatchException;
public class TryCatchFinallyDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter numerator: ");
int a = sc.nextInt();
System.out.print("Enter denominator: ");
int b = sc.nextInt();
int result = a / b; // may throw ArithmeticException (divide by zero)
System.out.println("Result = " + result);
} catch (InputMismatchException ex) {
System.out.println("Invalid input: please enter integers only.");
} catch (ArithmeticException ex) {
System.out.println("Error: denominator cannot be zero.");
} finally {
sc.close(); // cleanup always happens
System.out.println("Scanner closed (finally block executed).");
}
}
}
Example 2: Using throws (and handling it in the caller)
Here, the method declares checked exceptions with throws. The caller uses try-catch to handle them. The finally block ensures the file reader is closed.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ThrowsDemo {
// Declares (does not handle) IOException
static String readFirstLine(String path) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(path)); // may throw IOException
return br.readLine();
} finally {
// finally ensures resource is closed even if an exception occurs above
if (br != null) {
br.close();
}
}
}
public static void main(String[] args) {
try {
String line = readFirstLine("data.txt");
System.out.println("First line: " + line);
} catch (IOException e) {
System.out.println("Failed to read file: " + e.getMessage());
}
}
}
How Control Flows
- Code inside try runs.
- If an exception occurs, control jumps to the first matching catch.
- After catch (or if no exception occurred), the finally block executes.
- If no catch matches and there is no caller handling it, the program terminates with an error.
Key Points for Exams and Interviews
- Use multiple catch blocks for different exception types. Put more specific exceptions before general ones.
- throws is for declaration (telling the caller), while try-catch is for handling.
- finally almost always executes, even if an exception is thrown. It may not run in rare cases like
System.exit(0)or JVM crash. - Avoid returning from finally; it can hide original exceptions and make debugging difficult.
- For resources, consider try-with-resources (Java 7+), which auto-closes resources:
// try-with-resources (auto-closes br)
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
System.out.println("I/O error: " + e.getMessage());
}
In summary, combine try, catch, throws, and finally to write safe, clean, and maintainable Java programs that handle errors gracefully.
