Q 121
Easy
What is the purpose of a try block?
Answer
A try block contains code that may throw an exception and needs exception handling.
Explanation
The try block defines the portion of code whose failures are handled by one or more matching catch blocks or followed by a finally block. It should contain the operation that may actually fail rather than wrapping a large unrelated section of application code.
Code Example
Java
try {
Student student = studentService.findById(studentId);
System.out.println(student.getName());
} catch (StudentNotFoundException e) {
System.out.println("Student was not found");
}
Reference:
Java Exception Handling