Java Errors and Exceptions

Both Errors and Exceptions are the subclasses of java.lang.Throwable class. Errors should not be caught or handled (except in the rarest of cases). Exceptions are the bread and butter of exception handling. An Error "indicates serious problems that a reasonable application should not try to catch." While, an Exception "indicates conditions that a reasonable application might want to catch." Errors tend to signal the end of your application as you know it. It typically cannot be recovered from and should cause your Virtual Machine to exit. Catching them should not be done except to possibly log or display and appropriate message before exiting. Mostly Error is thrown by JVM in a scenario which is fatal and there is no way for the application program to recover from that error. For instance OutOfMemoryError .

There are three kinds of errors:

  1. Syntax Errors
  2. Runtime Errors
  3. Logic Errors

Syntax errors

Syntax errors are errors where the compiler finds something wrong with your Java program , and you can't even try to run it. For example, you may have incorrect punctuation, or may be trying to use a variable that hasn't been declared. These errors are the easiest to find and correct. The compiler will tell you where it got into problems, and its best guess as to what you did wrong.

Runtime errors


java runtime errors
Runtime errors occur when a program with no syntax errors asks the computer to do something that the computer is unable to reliably do . Common examples are:
  1. Trying to divide by a variable that contains a value of zero.
  2. Trying to open a file that doesn't exist.
Runtime errors are intermediate in difficulty. JVM tells you where it discovered that your program had gone wrong , but you need to trace back from there to figure out where the problem originated.

Logic errors

Logic errors occur when a program does not perform the way it was intended to . The JVM, of course, has no idea what your program is supposed to do , so it provides no additional information to help you find the error. Common examples are:
  1. Multiplying when you should be dividing
  2. Adding when you should be subtracting
  3. Opening and using data from the wrong file
  4. Displaying the wrong message

Java Errors and Exceptions
In general, syntax errors are easy to find and easy to correct because the compiler gives indications as to where the errors came from and why they are wrong. Runtime errors are not difficult to find, either, since the reasons and locations for the errors are displayed on the console when the program aborts. Finding logic errors , on the other hand, can be very challenging.