Types of Error in Java
Error in Java:
An error may produce an incorrect output or may terminate the execution of the program abruptly.
Types of Error:
Errors may broadly be classified into two categories:
- Compile-Time Errors
- Run-Time Errors
Compile-Time Errors:
All the syntax errors will be detected and displayed by the Java compiler and therefore these errors are known as compile-time errors. Whenever the compiler displays an error. It will not create the .class file.
Most of the compile-time errors are due to typing mistakes. Typographical errors are hard to find. We may have to check the code word by word or even character by character. The most common Run-Time Errors are:
1. Missing semicolons
2. Missing or mismatch of brackets in classes and methods.
3. Misspelling of identifiers and keywords.
4. Missing double quotes in strings.
5. Use of undeclared variables
6. Use of = in place of = = operator
Example:
class Error { public static void main(String args[]) { System.out.println("Welcome to Webeduclick!") // Missing ; } }
Run-Time Errors:
Sometimes, a program may compile successfully creating the .class file but it may not run properly. Such programs may produce wrong results due to wrong logic or it may terminate due to errors that are called Run-Time Errors. The most common Run-Time Errors are:
1. Dividing an integer by zero
2. Accessing an element that is out of the bounds of an array
3. Trying to store a value into an array of an incompatible class or type
4. Trying to cast an instance of a class to one of its subclasses
5. Passing a parameter that is not in a valid range or value for a method
6. Trying to illegally change the state of a thread.
Example:
class Test { public static void main(String args[]) { int x=10, y=5, z=5; int k=x/(y-z); // Division by zero System.out.println("K="+k); int m=x/(y+z); System.out.println("M="+m); } }