Errors are the wrongs that can make a program go wrong. In computer terminology errors may be referred to as bugs. It is common to make mistakes while developing as well as typing a program. A mistake might lead to an error causing to program to produce unexpected results. An error may produce an incorrect output or may terminate the execution of the program abruptly or even may cause the system to crash. It is therefore important to detect and manage properly all the possible errors.
Types of Errors: Errors may broadly be classified into two categories:
• Compile-time errors
• Run-time errors
Compile-Time Errors: All 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. It is necessary to fix these errors to get it compiled. It becomes an easy job to a programmer to correct these errors because Java compiler tells us where the errors are. 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 errors are:
• Missing semicolons
• Missing (or mismatch of) brackets in classes and methods
• Misspelling of identifiers and keywords
• Missing double quotes in strings
• Use of undeclared variables Incompatible types in assignments / initialization
• Bad references to objects
• Use of = in place of = = operator
Run-Time Errors: Sometimes, a program may compile successfully creating the .class file but may not run properly. Such programs may produce wrong results due to wrong logic or may terminate due to errors such as stack overflow. Most common run-time errors are:
• Dividing an integer by zero
• Accessing an element that is out of the bounds of an array
• Trying to store a value into an array of an incompatible class or type
• Trying to cast an instance of a class to one of its subclasses
• Passing a parameter that is not in a valid range or value for a method
• Trying to illegally change the state of a thread
• Attempting to use a negative size for an array
• Using a null object reference to access a method or a variable.
• Converting invalid string to a number
• Accessing a character that is out of bounds of a string
Example: The following code generates division-by-zero runtime error.
int x=5, y=0;
System.out.println(x/y);
It displays the following message and stops without executing further statements.
Java.lang.ArithmeticException: / by zero
0 comments:
Post a Comment