Romanage Dan
June 22nd, 2010, 16:11
I'll be taking care of this thread from now on, if you have a compiler/runtime error not listed post it and I'll add it.
Most errors were composed by Project Evolution.
Common Java Exceptions[/size] By (Dan)
Compiler Errors
This error happens to be a very common problem with beginners. This error is derived from a missing or having too many left or right brace brackets, { and }. 100 errors omit in private servers because that's the maximum the java compiler will output on default settings.
public class Example {
public int errors() {
return 0;
}
public void moreErrors() {
public static void main(String[] args) {
System.out.println("This is an example of 100 errors!");
}
}
This wont throw the legendary 100 errors because the code is to small, but the concept is the same. There is a missing bracket and because of this we get a silly error. Obviously, we need to add another bracket.
public class Example {
public int errors() {
return 0;
}
public void moreErrors() {
}
public static void main(String[] args) {
System.out.println("Correct number of brackets!");
}
}
Cannot Find Symbol
Another common pitfall for novices. This error means a certain variable or method cannot be found or hasnt been defined. Usually this is the case when the variable or method is located in a different class. Take a look,
public class ClassOne {
private int aVariable = 2;
public int getAVariable() {
return aVariable;
}
}
public class ClassTwo {
public void printTheAVariable() {
int variable = getAVariable();
System.out.println(variable);
}
}
They are both two different classes, and the objective is we want to print the aVariable located in the ClassOne class from the printTheAVariable() in the ClassTwo class. But we get an error, cannot find symbol. Whats the problem? Well, we didnt make a reference to the ClassOne class, so how do we expect the compiler to know what we are asking for? We simply instantiate the ClassOne class like so,
ClassOne classOne = new ClassOne();[/code]However we are not done. Now we need to reference our getAVariable() method. Here is what I mean,
public void printTheAVariable() {
int variable = classOne.getAVariable();
System.out.println(variable);
}This will call the getAVariable() method from the ClassOne class! If done correctly, it will print out the aVariable integer: 2.
What if we wanted to call the aVariable in ClassOne instead of the getAVariable()? "I referenced correctly but it gives me a 'variable has private access' error." Well, thats going to be discussed in the next section. Also, this also partly applies to static variables/methods, read here
Here is an exercise for you to work on,
public class PlayerLevel {
public int playerLevel = 126;
}
public class PrintPlayerLevel {
public void printPlayerLevel() {
int playerCbLevel = playerLevel;
sendMessage(playerCbLevel);
}
} Figure out how to fix it.
Variable has Private Access
This is an error which applies to all methods/fields(variables) with the private modifier. For example,
private int aVariable = 2;These are methods/fields which arent called outside of the class it is within (however reflection is a different story iirc). Read up on these for more information,
Only the registered members can see the link.
Only the registered members can see the link.
Looking back at the other example, what happens when we try and call the aVariable from the ClassOne class like so,
public class ClassOne {
private int aVariable = 2;
public int getAVariable() {
return aVariable;
}
}
public class ClassTwo {
ClassOne classOne = new ClassOne();
public void printTheAVariable() {
int variable = classOne.aVariable;
System.out.println(variable);
}
} We get: aVariable has private access in ClassOne. Why? Well, if you read the links I put up above, private modifiers mean methods/fields are only available within the class it is in. How can we fix this? Simply, you can take advantage of the Accessor pattern by making a 'getter' method like so,
public int getAVariable() {
return aVariable;
} Which was already used in the first place. Or you can make the aVariable field public. Here is the correct code,
public class ClassOne {
public int aVariable = 2;
public int getAVariable() {
return aVariable;
}
}
public class ClassTwo {
ClassOne classOne = new ClassOne();
public void printTheAVariable() {
int variable = classOne.aVariable;
System.out.println(variable);
}
} This is self explanatory however here is a short excercise. Make a simple getter method for a variable named playerLevel. Look above if you dont understand.
; Expected
This is a pretty easy error. Like the error says, your missing a colon in the code. Colons are used to end expressions like so,
public boolean expression = true;
Colons are used a lot. "So why does my code give me a ; expected error?" Well, you obviously were missing a colon somewhere. Take a look at this example,
public void doSomething() {
System.out.println("Doing something...")
} Why was there a ; expected error? Look at the end of the println() method and figure it out, thats your exercise.
( or ) Expected
This error occurs when there are dominating (too many) left or right brackets, ( or ). Another obvious fix, a simple way to fix it is to find where there are too many left brackets against right brackets. Look at this example,
if (aVariable1 == aVariable2 {
// do something here
} As you can see a right bracket was missing. Here is the correction,
if (aVariable1 == aVariable2) {
// do something here
}
This also applies to methods like so,
System.out.println(variable)); That would give a ; expected, however the problem lies with the fact there is one too many right brackets.
Your exercise for this section is trying to fix this if statement,
if ((totalLevel + 1) - (totalLevel + (0+0)) { You dont have to focus on the variable or what this really does, the ovjective is to fix the brackets.
Code Too Large
This error is popping up more and more, and many people dont know why this happens. In a Jave method, its size cannot exceed 64KB. Why? Google it. What to do when this occurs? Well, you can split the one method into two parts. Say you have a method called parseIncomingPackets() (this is a RSPS reference) and it exceeded 64KB. A simple way to rid of this error would be to split it into two parts by creating a nother method such as parseIncomingPackets2(). Here is an example,
public void parseIncomingPackets() {
// 64KB, compiler gives an error
}Split up,
public void parseIncomingPackets() {
// below 64KB, no error
}
public void parseIncomingPackets2() {
// below 64KB, no error
}
Also, be noted you have to call the second method at one point probably like,
public void parseIncomingPackets() {
// your code here
parseIncomingPackets2();
}
[anchor=dupemethod]
Duplicate Method
This error occurs when a programmer attempts to put two of the same methods in a class like so,
class SomeClass {
public void doSomething() {
// do something
}
public void doSomething() {
// do something
}
}This would give a: doSomething is already defined in SomeClass error. An easy fix is to just remove the appropriate method. Its usually just removing an older method. However, there can be a workaround. Methods with the same name but different parameters are a different story. Read on,
Only the registered members can see the link.
These are called overloading methods. Here is an example of overloaded methods,
class SomeClass {
public void doSomething(Object object) {
// do something
}
public void doSomething() {
// do something
}
}As you can see, one of the doSomething() methods have a parameter which accepts an object. If you compile this class, you will not be given a duplicate method error. Your exercise is to create two different methods BOTH called getPlayer which one of them will accept a string called playerName and the other an integer called playerID.
[anchor=dupecase]
Duplicate Case Label
This error occurs when a programmer is using a switch statement (Only the registered members can see the link.) and attempts to compile when there are two of the same case labels. Here is an example of a duplicate case label,
switch (expression) {
case 1:
// do something
break;
case 2:
// do something
break;
case 2:
// do something
break;
}Notice carefully and you will see two cases labelled with the number 2. This isnt allowed by the compiler so a fix would be like so,
switch (expression) {
case 1:
// do something
break;
case 2:
// do something
break;
case 3:
// do something
break;
}You cant have multiple case labels. There is no exercise for this section.
[anchor=nortrntype]
Missing Return Type
A missing return type error indicates a method with no return type. A return type can be of an integer, boolean, char, string, etc. However this is not the case with constructors. Read up on constructors,
Only the registered members can see the link.
Say we have a method like so,
public doSomething() {
// do something here
}Why is it the compiler returns a missing return type error? Its due to the fact doSomething has no return type, unless the class was named doSomething it wouldnt invoke an error becasue its a constructor. To fix such an error just place the return type you wish after the public modifier (or before the method name). Here is the fix,
public void doSomething() {
// do something here
}Remember that void isnt the only thing that can be used! You can use int, char, string, etc.
Study this snippet,
class DoSomething {
public DoSomething() {
// code goes here
}
}Does this give an error? Why or why doesnt it give an error?
[anchor=nortrnstment]
Missing Return Statement
Missing return statements tie in with the section we went over above. Return types (other than void) must return a value.
public int getInt() {
System.out.println("Called getInt!");
}This simple method displays a message on the console. But there is a problem, a missing return statement error was thrown. Why? Like it says, we need the method to actually return something. All methods with a return type other than void requires a return statement. So to wrap this up, the fix would be,
public int getInt() {
System.out.println("Called getInt!");
return anInteger;
}anInteger represents a variable which is of an integer. This also doesnt make a difference to boolean or other return types. Your exercise is to make a method with a boolean return type which will return a boolean variable called aBoolean.
[anchor=dupevar]
Variable Already Defined
A variable already defined error is similar to the duplicate method error. It means a variable is defined more than once. Take a look at this example which shows two local variables which would give the error,
private void doSomething() {
int number = 1;
int number = aVariable;
System.out.println(number);
}As you should be able to notice, the number variable is defined twice in the same method. Which isnt allowed. Same thing goes for global variables.
[anchor=nonstaticvar]
Non-static Variable Cannot be Referenced from a static context
This error comes up when a programmer attempts to use a variable without a static keyword with a method that does. You can read more on static here,
Only the registered members can see the link.
In the meantime, we have a class like so,
class StaticExample {
public int aVariable = 0;
public static int getAVariable() {
return aVariable;
}
}The problem lies with the aVariable. As you can see it has no static keyword. The fix would be to either make aVariable a static variable, or to make the getAVariable() method non-static. Very self-explanatory, a exercise shouldnt be needed.
[anchor=shldbedeclared]
Class ... is public, should be declared in...
This happens when a programmer tries to create a class that doesnt correspond to the name of the java file. Say for example we have a class named Client. Why would we get an error for having the following,
public class SomethingElse {
}The reason behind this is because the class is called SomethingElse when it really should be called Client. See the relationship? Heres an exercise (and perhaps a tricky one for beginners). If I had a constructor that was named after the java file, but NOT named after the class declaration (which is SomethingElse), would it work?
[anchor=unrprtexc]
Unreported Exception
An unreported exception error will be thrown if a snippet of code requires to be within a try/catch statement. Take a look at this example,
public void readFileInput() {
FileInputStream fis = new FileInputStream("file.txt");
}The problem with this code is it is necessary to have it closed in a try/catch block. To read more on those refer here,
Only the registered members can see the link.
In this case, a FileNotFoundException would be thrown if there happened to come an error. A fix would be to put all methods that require try/catch statements inside of one. Like so,
public void readFileInput() {
try {
FileInputStream fis = new FileInputStream("file.txt");
} catch (FileNotFoundException ex) {
// Handle error
}
} You also must import the class that corresponds to the exception. In this case you would need to import the FileNotFoundException class.
import java.io.FileNotFoundException;
[anchor=illstart]
Illegal Start of Expression
An illegal start of expression can come up even when code looks perfectly fine, some common problems with this error are listed below. Defining a static field in a method isnt allowed, if you were to do this,
public void aMethod() {
static int variable = 5;
}Another would be with unbalanced brace or regular brackets. Take a look at this if statement,
if (1+(11)) == 12)You can see here there is an extra bracket that isnt supposed to be there. This section will be updated more.
[anchor=appliedto]
... cannot be applied to ...
This error comes up when the programmer invokes a method with incorrect parameters (Only the registered members can see the link.). Say for example we have this class,
class SomeClass {
public void sendMessage(String message, boolean isStaff) {
// code here
}
public void run() {
sendMessage("This is a message");
// other codes here
}
}This would give us an error that sendMessage(java.lang.String, boolean) in SomeClass cannot be applied to (java.lang.String). There is a simple explanation, due to the fact the sendMessage() method has two parameters; a string and a boolean, we only invoked the method with a string. To resolve this problem, we would also call sendMessage() with a string and boolean. This would be the fix,
class SomeClass {
public void sendMessage(String message, boolean isStaff) {
// code here
}
public void run() {
sendMessage("This is a message", true); // can be true or false
// other codes here
}
}This also applies to whether its being called with a wrong type, too little or too many parameters. An exercise for you is, would having two different sendMessage() methods with different parameters fix the problem?
[anchor=elsewoutif]
Else without if
An else without if error is pretty self explanatory, but I will go over it anyways. The result of such an error happens when using if statements or else/else if statements. Basically, a rule applies to else/else if statements - they need to have a beginning expression. What this means, is there needs to be an if statement before any else/else if statements. This is WRONG,
else {
// shit here
}This is correct,
if (expression) {
// shit here
} else {
// shit here
}
This is WRONG,
else if (expression) {
// shit here
} else {
// shit here
}
This is correct,
if (expression) {
// shit here
} else if (expression) {
// shit here
} else {
// shit here
}
Hopefully you get the point.
[anchor=reachedend]
Reached end of file while parsing
This error is thrown when you are missing a bracket near the end of your class.
public class Example {
public static void main(String args[]) {
//Do Stuff
}
As you can see in this case, the class was left unclosed. It should be written as
public class Example {
public static void main(String args[]) {
//Do Stuff
}
}
Its a very simple fix, unlike finding your missing bracket in 100 errors, you can simply go to the end of your class and have look around :)
[anchor=packagenoexist]
package ... does not exist
Thrown when importing a nonexistant package.
import java.io.inPutStream;
The package you import has to exist. Naturally, its case sensitive.
import java.io.InputStream;
If your importing from your own source files, the package is the folders leading up to the class.
import com.rs2.server.Server; // Imports Server class
For more info: Only the registered members can see the link.
[anchor=orphancase]Orphaned Case
An orphaned case is a case that is lying outside of a switch statement
switch (example) {
case 1:
//Stuff
break;
case 2:
//Stuff
break;
}
case 3:
//Orphaned Case
break;
As you can see, the case was declared after the statement was closed.
This is a common error and quite easy to fix, simply A.) Move the case inside a switch statement, or B.) Surround the case with a switch statement
switch (example) {
case 1:
//Stuff
break;
case 2:
//Stuff
break;
case 3:
//Stuff
break;
}
[anchor=trycatch]'try' without 'catch' or 'finally'
You wrote a code can throw an exception, but failed to surround it with try, catch/finally
but failed to end with catch of finally.
public static void main(String[] args) {
new java.net.ServerSocket(43594, 1, null); //Wrong
}
This would throw the error. Its pretty easy to fix, you just need to add catch with the appropriate exception (see Java Exceptions (Only the registered members can see the link._exceptions))
public static void main(String[] args) {
try {
new java.net.ServerSocket(43594, 1, null);
} catch (IOException e) {
e.printStackTrace();
}
}
Alternatively, you can add a throw to the method.
public static void main(String[] args) throws IOException {
new java.net.ServerSocket(43594, 1, null);
}
Lets break it down for better understanding.
public static void main(String[] args) {
try {
new java.net.ServerSocket(43594, 1, null);
} catch (IOException e) {
e.printStackTrace();
}
}
First, it is going to try to bind to port 43594, if it cannot than it will throw the IOException. printStackTrace will print out the details of the exception.
I realize I fail at explaining things in detail, but that's the general idea :|
[hr]
Common Java Exceptions By (Zam)[/b
[b]java.lang
ClassCastException - Occurs when you try to cast an object to a class which is not it's subclass, sub interface, or class.
Example:
RsObject rsObject = new RsObject();
WowObject wowObject = (WowObject) rsObject; // This line would throw a ClassCastException as rsObject is not a WowObject.
ArrayIndexOutOfBoundsException - Thrown when you try to access an index on an array which doesn't exist.
Example:
Object[] array = new Object[200];
Object obj = array[200]; // Would throw an ArrayIndexOutOfBoundsException as the array indices start at 0 meaning max is 199.
NullPointerException - Thrown when you try to use an object reference who's value is null.
Example:
Object object = null;
object.notify(); // Would throw NullPointerException as the object to which object points is null.
java.util
ConcurrentModificationException - Thrown when multiple threads try to read/modify an object at the same time. Multiple threads can read at the same time but multiple threads can't write at the same time, or read and write at the same time.
java.io
FileNotFoundException - Gets thrown when you try to load a file that doesn't exist.
IOException - Thrown when an errors occurs with Input/Output, this may be a reading or writing to a stream or channel problem.
NotSerializableException - Thrown when you try to serialize an object that doesn't implement Serializable.
(sorry there was some errors. im only 9 and i cant do all these things :) thank you)
Most errors were composed by Project Evolution.
Common Java Exceptions[/size] By (Dan)
Compiler Errors
This error happens to be a very common problem with beginners. This error is derived from a missing or having too many left or right brace brackets, { and }. 100 errors omit in private servers because that's the maximum the java compiler will output on default settings.
public class Example {
public int errors() {
return 0;
}
public void moreErrors() {
public static void main(String[] args) {
System.out.println("This is an example of 100 errors!");
}
}
This wont throw the legendary 100 errors because the code is to small, but the concept is the same. There is a missing bracket and because of this we get a silly error. Obviously, we need to add another bracket.
public class Example {
public int errors() {
return 0;
}
public void moreErrors() {
}
public static void main(String[] args) {
System.out.println("Correct number of brackets!");
}
}
Cannot Find Symbol
Another common pitfall for novices. This error means a certain variable or method cannot be found or hasnt been defined. Usually this is the case when the variable or method is located in a different class. Take a look,
public class ClassOne {
private int aVariable = 2;
public int getAVariable() {
return aVariable;
}
}
public class ClassTwo {
public void printTheAVariable() {
int variable = getAVariable();
System.out.println(variable);
}
}
They are both two different classes, and the objective is we want to print the aVariable located in the ClassOne class from the printTheAVariable() in the ClassTwo class. But we get an error, cannot find symbol. Whats the problem? Well, we didnt make a reference to the ClassOne class, so how do we expect the compiler to know what we are asking for? We simply instantiate the ClassOne class like so,
ClassOne classOne = new ClassOne();[/code]However we are not done. Now we need to reference our getAVariable() method. Here is what I mean,
public void printTheAVariable() {
int variable = classOne.getAVariable();
System.out.println(variable);
}This will call the getAVariable() method from the ClassOne class! If done correctly, it will print out the aVariable integer: 2.
What if we wanted to call the aVariable in ClassOne instead of the getAVariable()? "I referenced correctly but it gives me a 'variable has private access' error." Well, thats going to be discussed in the next section. Also, this also partly applies to static variables/methods, read here
Here is an exercise for you to work on,
public class PlayerLevel {
public int playerLevel = 126;
}
public class PrintPlayerLevel {
public void printPlayerLevel() {
int playerCbLevel = playerLevel;
sendMessage(playerCbLevel);
}
} Figure out how to fix it.
Variable has Private Access
This is an error which applies to all methods/fields(variables) with the private modifier. For example,
private int aVariable = 2;These are methods/fields which arent called outside of the class it is within (however reflection is a different story iirc). Read up on these for more information,
Only the registered members can see the link.
Only the registered members can see the link.
Looking back at the other example, what happens when we try and call the aVariable from the ClassOne class like so,
public class ClassOne {
private int aVariable = 2;
public int getAVariable() {
return aVariable;
}
}
public class ClassTwo {
ClassOne classOne = new ClassOne();
public void printTheAVariable() {
int variable = classOne.aVariable;
System.out.println(variable);
}
} We get: aVariable has private access in ClassOne. Why? Well, if you read the links I put up above, private modifiers mean methods/fields are only available within the class it is in. How can we fix this? Simply, you can take advantage of the Accessor pattern by making a 'getter' method like so,
public int getAVariable() {
return aVariable;
} Which was already used in the first place. Or you can make the aVariable field public. Here is the correct code,
public class ClassOne {
public int aVariable = 2;
public int getAVariable() {
return aVariable;
}
}
public class ClassTwo {
ClassOne classOne = new ClassOne();
public void printTheAVariable() {
int variable = classOne.aVariable;
System.out.println(variable);
}
} This is self explanatory however here is a short excercise. Make a simple getter method for a variable named playerLevel. Look above if you dont understand.
; Expected
This is a pretty easy error. Like the error says, your missing a colon in the code. Colons are used to end expressions like so,
public boolean expression = true;
Colons are used a lot. "So why does my code give me a ; expected error?" Well, you obviously were missing a colon somewhere. Take a look at this example,
public void doSomething() {
System.out.println("Doing something...")
} Why was there a ; expected error? Look at the end of the println() method and figure it out, thats your exercise.
( or ) Expected
This error occurs when there are dominating (too many) left or right brackets, ( or ). Another obvious fix, a simple way to fix it is to find where there are too many left brackets against right brackets. Look at this example,
if (aVariable1 == aVariable2 {
// do something here
} As you can see a right bracket was missing. Here is the correction,
if (aVariable1 == aVariable2) {
// do something here
}
This also applies to methods like so,
System.out.println(variable)); That would give a ; expected, however the problem lies with the fact there is one too many right brackets.
Your exercise for this section is trying to fix this if statement,
if ((totalLevel + 1) - (totalLevel + (0+0)) { You dont have to focus on the variable or what this really does, the ovjective is to fix the brackets.
Code Too Large
This error is popping up more and more, and many people dont know why this happens. In a Jave method, its size cannot exceed 64KB. Why? Google it. What to do when this occurs? Well, you can split the one method into two parts. Say you have a method called parseIncomingPackets() (this is a RSPS reference) and it exceeded 64KB. A simple way to rid of this error would be to split it into two parts by creating a nother method such as parseIncomingPackets2(). Here is an example,
public void parseIncomingPackets() {
// 64KB, compiler gives an error
}Split up,
public void parseIncomingPackets() {
// below 64KB, no error
}
public void parseIncomingPackets2() {
// below 64KB, no error
}
Also, be noted you have to call the second method at one point probably like,
public void parseIncomingPackets() {
// your code here
parseIncomingPackets2();
}
[anchor=dupemethod]
Duplicate Method
This error occurs when a programmer attempts to put two of the same methods in a class like so,
class SomeClass {
public void doSomething() {
// do something
}
public void doSomething() {
// do something
}
}This would give a: doSomething is already defined in SomeClass error. An easy fix is to just remove the appropriate method. Its usually just removing an older method. However, there can be a workaround. Methods with the same name but different parameters are a different story. Read on,
Only the registered members can see the link.
These are called overloading methods. Here is an example of overloaded methods,
class SomeClass {
public void doSomething(Object object) {
// do something
}
public void doSomething() {
// do something
}
}As you can see, one of the doSomething() methods have a parameter which accepts an object. If you compile this class, you will not be given a duplicate method error. Your exercise is to create two different methods BOTH called getPlayer which one of them will accept a string called playerName and the other an integer called playerID.
[anchor=dupecase]
Duplicate Case Label
This error occurs when a programmer is using a switch statement (Only the registered members can see the link.) and attempts to compile when there are two of the same case labels. Here is an example of a duplicate case label,
switch (expression) {
case 1:
// do something
break;
case 2:
// do something
break;
case 2:
// do something
break;
}Notice carefully and you will see two cases labelled with the number 2. This isnt allowed by the compiler so a fix would be like so,
switch (expression) {
case 1:
// do something
break;
case 2:
// do something
break;
case 3:
// do something
break;
}You cant have multiple case labels. There is no exercise for this section.
[anchor=nortrntype]
Missing Return Type
A missing return type error indicates a method with no return type. A return type can be of an integer, boolean, char, string, etc. However this is not the case with constructors. Read up on constructors,
Only the registered members can see the link.
Say we have a method like so,
public doSomething() {
// do something here
}Why is it the compiler returns a missing return type error? Its due to the fact doSomething has no return type, unless the class was named doSomething it wouldnt invoke an error becasue its a constructor. To fix such an error just place the return type you wish after the public modifier (or before the method name). Here is the fix,
public void doSomething() {
// do something here
}Remember that void isnt the only thing that can be used! You can use int, char, string, etc.
Study this snippet,
class DoSomething {
public DoSomething() {
// code goes here
}
}Does this give an error? Why or why doesnt it give an error?
[anchor=nortrnstment]
Missing Return Statement
Missing return statements tie in with the section we went over above. Return types (other than void) must return a value.
public int getInt() {
System.out.println("Called getInt!");
}This simple method displays a message on the console. But there is a problem, a missing return statement error was thrown. Why? Like it says, we need the method to actually return something. All methods with a return type other than void requires a return statement. So to wrap this up, the fix would be,
public int getInt() {
System.out.println("Called getInt!");
return anInteger;
}anInteger represents a variable which is of an integer. This also doesnt make a difference to boolean or other return types. Your exercise is to make a method with a boolean return type which will return a boolean variable called aBoolean.
[anchor=dupevar]
Variable Already Defined
A variable already defined error is similar to the duplicate method error. It means a variable is defined more than once. Take a look at this example which shows two local variables which would give the error,
private void doSomething() {
int number = 1;
int number = aVariable;
System.out.println(number);
}As you should be able to notice, the number variable is defined twice in the same method. Which isnt allowed. Same thing goes for global variables.
[anchor=nonstaticvar]
Non-static Variable Cannot be Referenced from a static context
This error comes up when a programmer attempts to use a variable without a static keyword with a method that does. You can read more on static here,
Only the registered members can see the link.
In the meantime, we have a class like so,
class StaticExample {
public int aVariable = 0;
public static int getAVariable() {
return aVariable;
}
}The problem lies with the aVariable. As you can see it has no static keyword. The fix would be to either make aVariable a static variable, or to make the getAVariable() method non-static. Very self-explanatory, a exercise shouldnt be needed.
[anchor=shldbedeclared]
Class ... is public, should be declared in...
This happens when a programmer tries to create a class that doesnt correspond to the name of the java file. Say for example we have a class named Client. Why would we get an error for having the following,
public class SomethingElse {
}The reason behind this is because the class is called SomethingElse when it really should be called Client. See the relationship? Heres an exercise (and perhaps a tricky one for beginners). If I had a constructor that was named after the java file, but NOT named after the class declaration (which is SomethingElse), would it work?
[anchor=unrprtexc]
Unreported Exception
An unreported exception error will be thrown if a snippet of code requires to be within a try/catch statement. Take a look at this example,
public void readFileInput() {
FileInputStream fis = new FileInputStream("file.txt");
}The problem with this code is it is necessary to have it closed in a try/catch block. To read more on those refer here,
Only the registered members can see the link.
In this case, a FileNotFoundException would be thrown if there happened to come an error. A fix would be to put all methods that require try/catch statements inside of one. Like so,
public void readFileInput() {
try {
FileInputStream fis = new FileInputStream("file.txt");
} catch (FileNotFoundException ex) {
// Handle error
}
} You also must import the class that corresponds to the exception. In this case you would need to import the FileNotFoundException class.
import java.io.FileNotFoundException;
[anchor=illstart]
Illegal Start of Expression
An illegal start of expression can come up even when code looks perfectly fine, some common problems with this error are listed below. Defining a static field in a method isnt allowed, if you were to do this,
public void aMethod() {
static int variable = 5;
}Another would be with unbalanced brace or regular brackets. Take a look at this if statement,
if (1+(11)) == 12)You can see here there is an extra bracket that isnt supposed to be there. This section will be updated more.
[anchor=appliedto]
... cannot be applied to ...
This error comes up when the programmer invokes a method with incorrect parameters (Only the registered members can see the link.). Say for example we have this class,
class SomeClass {
public void sendMessage(String message, boolean isStaff) {
// code here
}
public void run() {
sendMessage("This is a message");
// other codes here
}
}This would give us an error that sendMessage(java.lang.String, boolean) in SomeClass cannot be applied to (java.lang.String). There is a simple explanation, due to the fact the sendMessage() method has two parameters; a string and a boolean, we only invoked the method with a string. To resolve this problem, we would also call sendMessage() with a string and boolean. This would be the fix,
class SomeClass {
public void sendMessage(String message, boolean isStaff) {
// code here
}
public void run() {
sendMessage("This is a message", true); // can be true or false
// other codes here
}
}This also applies to whether its being called with a wrong type, too little or too many parameters. An exercise for you is, would having two different sendMessage() methods with different parameters fix the problem?
[anchor=elsewoutif]
Else without if
An else without if error is pretty self explanatory, but I will go over it anyways. The result of such an error happens when using if statements or else/else if statements. Basically, a rule applies to else/else if statements - they need to have a beginning expression. What this means, is there needs to be an if statement before any else/else if statements. This is WRONG,
else {
// shit here
}This is correct,
if (expression) {
// shit here
} else {
// shit here
}
This is WRONG,
else if (expression) {
// shit here
} else {
// shit here
}
This is correct,
if (expression) {
// shit here
} else if (expression) {
// shit here
} else {
// shit here
}
Hopefully you get the point.
[anchor=reachedend]
Reached end of file while parsing
This error is thrown when you are missing a bracket near the end of your class.
public class Example {
public static void main(String args[]) {
//Do Stuff
}
As you can see in this case, the class was left unclosed. It should be written as
public class Example {
public static void main(String args[]) {
//Do Stuff
}
}
Its a very simple fix, unlike finding your missing bracket in 100 errors, you can simply go to the end of your class and have look around :)
[anchor=packagenoexist]
package ... does not exist
Thrown when importing a nonexistant package.
import java.io.inPutStream;
The package you import has to exist. Naturally, its case sensitive.
import java.io.InputStream;
If your importing from your own source files, the package is the folders leading up to the class.
import com.rs2.server.Server; // Imports Server class
For more info: Only the registered members can see the link.
[anchor=orphancase]Orphaned Case
An orphaned case is a case that is lying outside of a switch statement
switch (example) {
case 1:
//Stuff
break;
case 2:
//Stuff
break;
}
case 3:
//Orphaned Case
break;
As you can see, the case was declared after the statement was closed.
This is a common error and quite easy to fix, simply A.) Move the case inside a switch statement, or B.) Surround the case with a switch statement
switch (example) {
case 1:
//Stuff
break;
case 2:
//Stuff
break;
case 3:
//Stuff
break;
}
[anchor=trycatch]'try' without 'catch' or 'finally'
You wrote a code can throw an exception, but failed to surround it with try, catch/finally
but failed to end with catch of finally.
public static void main(String[] args) {
new java.net.ServerSocket(43594, 1, null); //Wrong
}
This would throw the error. Its pretty easy to fix, you just need to add catch with the appropriate exception (see Java Exceptions (Only the registered members can see the link._exceptions))
public static void main(String[] args) {
try {
new java.net.ServerSocket(43594, 1, null);
} catch (IOException e) {
e.printStackTrace();
}
}
Alternatively, you can add a throw to the method.
public static void main(String[] args) throws IOException {
new java.net.ServerSocket(43594, 1, null);
}
Lets break it down for better understanding.
public static void main(String[] args) {
try {
new java.net.ServerSocket(43594, 1, null);
} catch (IOException e) {
e.printStackTrace();
}
}
First, it is going to try to bind to port 43594, if it cannot than it will throw the IOException. printStackTrace will print out the details of the exception.
I realize I fail at explaining things in detail, but that's the general idea :|
[hr]
Common Java Exceptions By (Zam)[/b
[b]java.lang
ClassCastException - Occurs when you try to cast an object to a class which is not it's subclass, sub interface, or class.
Example:
RsObject rsObject = new RsObject();
WowObject wowObject = (WowObject) rsObject; // This line would throw a ClassCastException as rsObject is not a WowObject.
ArrayIndexOutOfBoundsException - Thrown when you try to access an index on an array which doesn't exist.
Example:
Object[] array = new Object[200];
Object obj = array[200]; // Would throw an ArrayIndexOutOfBoundsException as the array indices start at 0 meaning max is 199.
NullPointerException - Thrown when you try to use an object reference who's value is null.
Example:
Object object = null;
object.notify(); // Would throw NullPointerException as the object to which object points is null.
java.util
ConcurrentModificationException - Thrown when multiple threads try to read/modify an object at the same time. Multiple threads can read at the same time but multiple threads can't write at the same time, or read and write at the same time.
java.io
FileNotFoundException - Gets thrown when you try to load a file that doesn't exist.
IOException - Thrown when an errors occurs with Input/Output, this may be a reading or writing to a stream or channel problem.
NotSerializableException - Thrown when you try to serialize an object that doesn't implement Serializable.
(sorry there was some errors. im only 9 and i cant do all these things :) thank you)