8.4: Exception Handling
Read this chapter.
Both exceptions and errors are problems that may happen when a program is running. They can disrupt the normal execution of the program and halt the program abruptly. An exception is usually external to the program such as invalid values from an input and output device, which can be recovered so that the program can resume execution, while an error is usually severe so that the program has to be stopped. Java uses Exception class to hold information about the exception and Error class But Read first three pages of the resource to understand the difference between exception and error. In Java, both Exception class and Error class are derived from a class called "throwable."
At the very core of exception handling mechanism are the keywords try and catch. They work together to catch and fix problems in a program. The try block contains code that might throw an exception while the catch block contains code that handles the exception.
Once an execution of a program stops due to a problem, JVM's default exception handler terminates program execution and displays an error message followed by a list of method calls that lead to the exception. This is referred to as stack trace.
Watch this video as it demonstrates the use of try and catch blocks to catch exceptions in a simple Java program.
Attempt this ungraded quiz.