Sabtu, 07 November 2015

Jenis-jenis Error pada Java



Dalam Bahasa pemrograman Java terdapat beberapa klasifikasi error / kesalahan berdasarkan pesan kesalahan atau error message yang ditampilkan. Berikut klasifikasi jenis-jenis error pada Java

Syntax Error

• . . . expected
if (i > j // Error, unbalanced parentheses max = i // Error, missing semicolon
else
max = j;

• unclosed string literal
String longString = "This is first half of a long string " + "and this is the second half.";

• illegal start of expression
if (i > j) ) // Error, extra parenthesis max = i;

• not a statement
max ; // Error, missing =

Identifier

• cannot find symbol
int[] a = {1, 2, 3}; int sum = 0; for (int i = 0; i < a.length; i++) { sum = sum + a[i]; } System.out.println("Last = " + i); // Error, i not in scope

• . . . is already defined in . . .
int sum = 0; double sum = 0.0; // Error, sum already defined

• array required but . . . found
int max(int i, int j) { if (i > j) return i;
else return j[i]; // Error, j is not an array
} Computation

• variable . . . might not have been initialized
void m(int n) { // n is initialized from the actual parameter
int i, j;
i = 2; // i is initialized by the assignment
int k = 1; // k is initialized in its declaration
if (i == n) // OK
k = j; // Error, j is not initialized
else
j = k;
}

• incompatible types
boolean b = true; int a = b; // Error, can’t assign boolean to int

• operator . . . cannot be applied to . . . ,. . .
int a = 5;
 boolean b = true;
 int c = a + b; // Error, can’t add a boolean value
 double d = a + 1.4; // OK, int is implicitly converted to double

• inconvertible types
boolean b = true;
int x = (int) b; // Error, can’t convert boolean to int

• missing return statement
int max(int i, int j) {
if (i > j)
 return i;
else if (i <= j)
 return j; // Error: what about the path when i>j and i<=j are both false?!!
}

• missing return value
int max(int i, int j) {
 return; // Error, missing int expression
}

• cannot return a value from method whose result type is void
void m(int i, int j) { return i + j; // Error, the method was declared void }

• invalid method declaration; return type required
max(int i, int j) { ... }
 class MyClass { MyClass(int i) { ... }
 Myclass(int i, int j) { ... } // Error because of the lowercase c }

• unreachable statement
void m(int j)
{ System.out.println("Value is " + j);
return;
j++; }
 if (true) {
return n + 1; // Only this alternative executed, but ...
} else { return n - 1; n = n + 1; // ... this is an error }

• ArrayIndexOutOfRange 
 final static int SIZE = 10;
 int a = new int[SIZE];
 for (int i = 0; i <= SIZE; i++) // Error,<= should be <
 for (int i = 0; i <= a.length; i++) // Better, but still an error

Computation

• outOfMemoryError int a = new int[100000000];

• StackOverFlowArea int factorial(int n) { if (n == 0) return 1;
else return n * factorial(n + 1); // Error, you meant n - 1
}




Read Another


CATEGORIES



0 Comment :