We can easily catch and handle errors in our programs so that they do not terminate abnormally. When a program terminates abnormally, typically it dumps some undecipherable messages to the user terminal. Worse is the case where GUI applications terminate abnormally and switch to a console mode, thus totally confusing the user. We better take care of such exceptions in our programs in order to provide a rich user experience.
To catch exception conditions in our program, Java provides a construct called the try-catch block. The susceptible code that may generate an exception at runtime is enclosed in a try block, and the exception-handling code is enclosed in a catch block. The syntax of a try-catch block is shown here
try {
blockStatements
} catch ( ExceptionType exceptionObjectName ) {
blockStatements
}
try {
// code that may generate a runtime or some kind of exception
} catch (Exception e) {
// your error handler
}
If an exception occurs while the code in the try block is being executed, the Java runtime creates an object of the Exception class, encapsulating the information on what went wrong, and transfers the program control to the first statement enclosed in the catch block. The code in the catch block analyses the information stored in the Exception object and takes the appropriate corrective action. The exception in the previous example can be handled gracefully by putting the susceptible printVisitorList method in a try-catch block, as shown here:
try {
roster.printVisitorList();
} catch (Exception e) {
System.out.println (" Quitting on end of list" );
}
...
Visitor ID # gc051hh3hba7
Visitor ID # i98ivsnwunp4
Visitor ID # rapll6ouc0m6
Quitting on end of list
As we can see in this example, the Java runtime always passes an Exception object to our exception handler. Because the types of exceptions or runtime errors that can occur in our application can be very large, it will be difficult to assimilate the information provided by a single Exception object. Therefore, the Exception class is categorized into several subclasses. We learn this categorization in the next post.
Hemant Patel
10-Mar-2017Thanks Zack for nice post also very informative blog about try-catch statements in java.A try block is always followed by a catch block, which handles the exception that occurs in associated try block.