In one of my prof slides on ploymorphism, I see this piece of code with a couple of comments:
discountVariable = //will produce
(DiscountSale)saleVariable;//run-time error
discountVariable = saleVariable //will produce
//compiler error
As you can see, it says in the first casting statement that it’ll produce run-time error and in the other one it says it’ll produce compiler error.
What makes these errors? and how they differ from each other?
The Unfun Cat
28.9k29 gold badges110 silver badges150 bronze badges
asked Feb 27, 2012 at 20:31
3
A run time error will only occur when the code is actually running.
These are the most difficult — and lead to program crashes and bugs in your code which can be hard to track down.
An example might be trying to convert a string: «hello» into an integer:
string helloWorld = "hello";
int willThrowRuntimeError = Convert.ToInt32(helloWorld);
The compiler may not see this as a problem but when run an error will be thrown.
Compiler errors are due to inaccuracies in code, where the compiler throws an error to alert you to something which will not compile, and therefore cannot be run.
An example of a compiler error would be:
int = "this is not an int";
user
4,8906 gold badges17 silver badges35 bronze badges
answered Feb 27, 2012 at 20:38
DIXONJWDDDIXONJWDD
1,25610 silver badges20 bronze badges
1
A runtime error happens during the running of the program. A compiler error happens when you try to compile the code.
If you are unable to compile your code, that is a compiler error.
If you compile and run your code, but then it fails during execution, that is runtime.
answered Feb 27, 2012 at 20:33
James MontagneJames Montagne
76.8k14 gold badges108 silver badges129 bronze badges
2
Compile time errors refers to syntax and semantics. For example, if you do operations that involves different types. Ex: adding a string with an int, or dividing a string by a real. (read the last paragraph thou!!!)
Run Time errors are those that are detected when the program execute. For example, division by zero. The compiler can not know if the operation x/a-b will leads to division by zero until the execution.
This is a very broad explanation. There are many smart compilers, and, also, is possible to do internal casting among different types that leads to operations that make sense. It it possible to pre-compile code and see some run time errors even if the code is not executed.
Refer to this link too: Runtime vs Compile time
answered Feb 27, 2012 at 20:37
Compile time errors are errors of syntax and semantics.
Run time errors are errors of logic primarily. Due to something the programmer has overlooked, the program crashes e.g. division by 0, accessing a variable without initializing it first etc.
answered Jun 8, 2015 at 7:03
HadiHadi
5008 silver badges20 bronze badges
Compile Time error means that the Compiler knows that discountVariable = saleVariable
must be end with a semi colon as belowdiscountVariable = saleVariable;
so it will throw an error when you compile the code.
Run Time error means that the error will occur at run time, because even though you are casting saleVariable into discountVariable, the cast cannot take because they differ in type.
answered Feb 27, 2012 at 20:33
CodeBlueCodeBlue
14.5k32 gold badges94 silver badges131 bronze badges
think you’ve already got the general desc of what’s the difference. Specifically in the code you have shown in the OP,
- In second statement, compiler compares the types on LHS and RHS and finds no implicit cast possible so it gives the error.
- first statement is seen by compiler as the same, but here programmer explicitly casts the type, which is as good as telling compiler that I know what I’m doing and of course the compiler trusts you and gives you no errors.
answered Feb 27, 2012 at 20:50
KashyapKashyap
14.5k12 gold badges63 silver badges100 bronze badges
1
Its because the compiler doesn’t know the object type of «saleVariable» until that value has actually been set when the program is running.
Your are forcing whatever is in salesVariable into the type DiscountSale this is considered unsafe and cannot be evaluated until runtime.
answered Feb 27, 2012 at 20:33
bigamilbigamil
6574 silver badges12 bronze badges
2
Compilation/Compile time/Syntax/Semantic errors: Compilation or compile time errors are error occurred due to typing mistake, if we do not follow the proper syntax and semantics of any programming language then compile time errors are thrown by the compiler. They wont let your program to execute a single line until you remove all the syntax errors or until you debug the compile time errors.
Example: Missing a semicolon in C or mistyping int
as Int
.
Runtime errors: Runtime errors are the errors that are generated when the program is in running state. These types of errors will cause your program to behave unexpectedly or may even kill your program. They are often referred as Exceptions.
Example: Suppose you are reading a file that doesn’t exist, will result in a runtime error.
Read more about all programming errors here
answered May 25, 2015 at 5:37
If you’d use Google, you’d get this:
Compile time error is any type of error that prevent a java program compile like a syntax error, a class not found, a bad file name for the defined class, a possible loss of precision when you are mixing different java data types and so on.
A runtime error means an error which happens, while the program is running. To deal with this kind of errors java define Exceptions. Exceptions are objects represents an abnormal condition in the flow of the program. It can be either checked or unchecked.
http://wiki.answers.com/Q/Difference_between_run_time_error_and_compile_time_error_in_java
answered Feb 27, 2012 at 20:32
2
Compiler errors are due to inaccuracies in code, where the compiler throws an error to alert you to something which will not compile, and therefore cannot be run.
Ex :- MethodOverloading
class OverloadingTest {
void sum(int a, long b) {
System.out.println("a method invoked");
}
void sum(long a, int b) {
System.out.println("b method invoked");
}
public static void main(String args[]) {
OverloadingTest obj = new OverloadingTest();
obj.sum(200, 200);// now ambiguity
}
}
Run Time errors are those that are detected when the program execute. For example, division by zero. The compiler can not know if the operation x/a-b will leads to division by zero until the execution
answered Apr 21, 2015 at 8:48
Nikhil KumarNikhil Kumar
2,5083 gold badges19 silver badges24 bronze badges
While working with the programming languages like executing a software program, there are many instances that we run into issues due to the run time errors or compilation errors. All these errors occur when the application is running. You might come across an instance where the application acts differently in a negative way to the requirements, then it means that a runtime error took place.
As it is one of the most common type of error that occurs during a software executive, let us get a deep idea on how to fix common types of runtime errors in Java and also the steps to be taken to resolve them on a timely basis.
Contents
- 1 Fix the 5 Most Common Types of Runtime Errors in Java
- 1.1 What is a Runtime Error in Java?
- 1.2 Differences Between Compile Time Error and Runtime Error in Java
- 1.3 Why Runtime Error Occurs in Java ?
- 1.4 1. Accessing Out of Range Value in an Array
- 1.5 2. Division by Zero Error
- 1.6 3. Less Space or Insufficient Space Memory Error
- 1.7 4. Conversion of an Invalid string into a Number
- 1.8 5. Attempting to Store an Incompatible Value to a Collection
- 1.9 How to solve Runtime Rrror in Java Programming?
Fix the 5 Most Common Types of Runtime Errors in Java
What is a Runtime Error in Java?
A runtime error in Java is referred to as an application error that comes up during the execution process of the program. This runtime error usually takes place when the syntax is corrected as expected while the issue lies during the program execution. All these errors can be detected by JVM – Java Virtual Machine and cannot be identified during the compilation time. Java is one of the most sought-after programming languages for the hiring managers across the world. So become an expert in Java through our Java Training and grab the best job opportunity.
Now, In this post, Let us discuss the top runtime errors in Java.
- Division by zero errors
- IO errors
- Out of range errors
- Undefined object errors
Differences Between Compile Time Error and Runtime Error in Java
Compile time errors are those errors in which the syntax would be incorrect in the application code. An example would be like missing semicolons, parenthesis, incorrect keywords, usage of undeclared variables, etc.
The Java compiler is capable of detecting the syntax errors during the compile time and the error message will be appearing on the screen. The compiler is also capable of preventing the code from the execution unless and until the error is resolved. Therefore it is important that these errors are addressed by making the necessary changes before the program is successfully executed.
The runtime errors occur during the program execution after the compilation has completed. Any program that is throwing a runtime error means that there are no issues with Syntax in the program.
Why Runtime Error Occurs in Java ?
Below listed are the most common types of runtime errors that occur in Java.
- Accessing an element that is out of range in an array
- Dividing a number with 0
- Less space or insufficient space memory
- Conversion of an invalid string into a number
- Attempting to store an incompatible value to a collection
When you come across such an address, you need to know that the Java compiler will be generating an error message and the program gets terminated abnormally. Runtime errors do not require to be caught explicitly. It is useful if you catch the runtime errors and resolve them to complete the program execution.
Let us review a few of the most common runtime errors in Java programming with examples to gain a deeper understanding.
1. Accessing Out of Range Value in an Array
public class ValueOutOfRangeErrorExample { public static void main(String[] args) { int k[] = new int[8]; System.out.println(«8th element in array: « + k[8]); } } |
In the above example, the array is initialized with 8 elements. with the above code, An element at position number 8 is trying to get access and does not exist at all, leading to the Exception java.lang.ArrayIndexOutOfBoundsException:
Error :
Exception in thread «main» java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 8 at ValueOutOfRangeErrorExample.main(ValueOutOfRangeErrorExample.java:4) |
2. Division by Zero Error
Below is an example of java.lang.ArithmeticException which occurs when the user is trying to code in such a way that they perform the division by zero.
public class ArithmeticExceptionExample { public static void main(String[] args) { int num1 = 10, num2 = 0; System.out.println(«Result: «+ num1/num2); } } |
In the above code, the integer num1 is getting to be divided by num2 which has a value of zero, which is leading to the exception called java.lang.ArithmeticException
Below is the Error Thrown :
Exception in thread «main» java.lang.ArithmeticException: / by zero at ArithmeticExceptionExample.main(ArithmeticExceptionExample.java:4) |
3. Less Space or Insufficient Space Memory Error
Below is an example of java.lang.OutOfMemoryError, which occurs when the user is trying to initialize an Integer array with a very large size, and due to the Java heap being insufficient to allocate this memory space, it throws an Error java.lang.OutOfMemoryError: Java heap space
public class OutOfMemory { public static void main(String[] args) { Integer[] myArray = new Integer[1000*1000*1000]; } } |
Error :
Exception in thread «main» java.lang.OutOfMemoryError: Java heap space at OutOfMemory.main(OutOfMemory.java:5) |
4. Conversion of an Invalid string into a Number
Below is an example of java.lang.NumberFormatException, occurs when the user is trying to convert an alphanumeric string to an integer which leads to java.lang.NumberFormatException
public class NumberFormatException { public static void main(String[] args) { int a; a= Integer.parseInt(«12Mehtab»); System.out.println(a); } } |
Error :
Exception in thread «main» java.lang.NumberFormatException: For input string: «12Mehtab» at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at NumberFormatException.main(NumberFormatException.java:6) |
5. Attempting to Store an Incompatible Value to a Collection
Below is an example where user has created the ArrayList of String but trying to store the integer value which leads to Exception java.lang.Error: Unresolved compilation problem
import java.util.ArrayList; public class IncompatibleType { public static void main(String[] args) { ArrayList<String> student = new ArrayList<>(); student.add(1); } } |
Error :
Exception in thread «main» java.lang.Error: Unresolved compilation problem: The method add(int, String) in the type ArrayList<String> is not applicable for the arguments (int) at IncompatibleType.main(IncompatibleType.java:7) |
How to solve Runtime Rrror in Java Programming?
The runtime errors can be solved by using the try catch blocks in Java. Below are the steps to be followed:
- You will need to Surround the statements that are capable of throwing an exception or a runtime error in the try catch blocks.
- The next step is to catch the error.
- Based on the requirements of the court or an application, it is important to take the necessary action.
Like we discussed earlier about the ArithmeticException example, it can be corrected by making the below changes.
public class ArithmeticExceptionExample { public static void main(String[] args) { try { int num1 = 10, num2 = 0; System.out.println(«Result: « + num1/num2); } catch (ArithmeticException ae) { System.out.println(«Arithmetic Exception — cannot divide by 0»); } System.out.println(«Let’s continue the execution…»); } } |
As the code is surrounded in the try catch blocks, the program will continue to execute after the exception is encountered.
Result :
Arithmetic Exception — cannot divide by 0 Let’s continue the execution... |
In this way, it is important for you to identify the Runtime errors and also clear them without any hesitation. You can make use of the try catch blocks and many other resolutions which were helped in successful program execution. Also you will be able to track, manage and analyze the errors in real time. So this was all from this tutorial about fixing the 5 most common types of Runtime Errors in Java But still, if you have any queries, feel free to ask in the comment section. And don’t forget to stay tuned with the Tutorials field to learn this type of awesome tutorial. HAPPY CODING.
People Are Also Reading…
- How to Play Mp3 File in Java Tutorial | Simple Steps
- Menu Driven Program in Java Using Switch Case
- Calculator Program in Java Swing/JFrame with Source Code
- Registration Form in Java With Database Connectivity
- How to Create Login Form in Java Swing
- Text to Speech in Java
- How to Create Splash Screen in Java
- Java Button Click Event
- 11 Best WebSites to Learn Java Online for Free
Errors in Java occur when a programmer violates the rules of Java programming language.
It might be due to programmer’s typing mistakes while developing a program. It may produce incorrect output or may terminate the execution of the program abnormally.
For example, if you use the right parenthesis in a Java program where a right brace is needed, you have made a syntax error. You have violated the rules of Java language.
Therefore, it is important to detect and fix properly all errors occurring in a program so that the program will not terminate during execution.
Types of Errors in Java Programming
When we write a program for the first time, it usually contains errors. These errors are mainly divided into three types:
1. Compile-time errors (Syntax errors)
2. Runtime errors
3. Logical errors
Compile-time errors occur when syntactical problems occur in a java program due to incorrect use of Java syntax.
These syntactical problems may be missing semicolons, missing brackets, misspelled keywords, use of undeclared variables, class not found, missing double-quote in Strings, and so on.
These problems occurring in a program are called syntax errors in Java.
Since all syntax errors are detected by Java compiler, therefore, these errors are also known as compile time errors in Java.
When Java compiler finds syntax errors in a program, it prevents the code from compile successfully and will not create a .class file until errors are not corrected. An error message will be displayed on the console screen.
These errors must be removed by debugging before successfully compile and run the program. Let’s take an example program where we will get a syntax error.
Program source code 1:
public class CompileTimeErrorEx { public static void main(String[] args) { System.out.println("a") // Syntax error. Semicolon missing. } }
Compile time error in Java code: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error, insert ";" to complete BlockStatements
When you will try to compile the above program, Java compiler will tell you where errors are in the program. Then you can go to the appropriate line, correct error, and recompile the program.
Let’s create a program where we will try to call the undeclared variable. In this case, we will get unresolved compilation problem.
Program source code 2:
public class MisspelledVar { public static void main(String[] args) { int x = 20, y = 30; // Declare variable sum. int sum = x + y; // Call variable Sum with Capital S. System.out.println("Sum of two numbers: " + Sum); // Calling of undeclared variable. } }
Compile time error in Java code: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Sum cannot be resolved to a variable
Program source code 3: Missing parenthesis in for statement.
public class MissingBracket { public static void main(String[] args) { int i; int sum = 0; // Missing bracket in for statement. for (i = 1; i <= 5; i++ // insert " ) Statement" to complete For Statement. { sum = sum + i; } System.out.println("Sum of 1 to 5 n"); System.out.println(sum); } }
Compile time error in Java code: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error, insert ") Statement" to complete ForStatement
Program source code 4: Missing double quote in String literal.
public class MissingDoubleQuote { public static void main(String[] args) { String str = "Scientech; // Missing double quote in String literal. System.out.println(str); } }
Compile time error in Java code: Exception in thread "main" java.lang.Error: Unresolved compilation problem: String literal is not properly closed by a double-quote
We may also face another error related to the directory path. An error such as
javac : command not found
means that you have not set the path correctly.
Runtime Errors in Java
Runtime errors occur when a program is successfully compiled creating the .class file but does not run properly. It is detected at run time (i.e. during the execution of the program).
Java compiler has no technique to detect runtime errors during compilation because a compiler does not have all of the runtime information available to it. JVM is responsible to detect runtime errors while the program is running.
Such a program that contains runtime errors, may produce wrong results due to wrong logic or terminate the program. These runtime errors are usually known as exceptions.
For example, if a user inputs a value of string type in a program but the computer is expecting an integer value, a runtime error will be generated.
The most common runtime errors are as follows:
1. Dividing an integer by zero.
2. Accessing an element that is out of range of the array.
3. Trying to store a value into an array that is not compatible type.
4. Passing an argument that is not in a valid range or valid value for a method.
5. Striving to use a negative size for an array.
6. Attempting to convert an invalid string into a number.
7. and many more.
When such errors are encountered in a program, Java generates an error message and terminates the program abnormally. To handle these kinds of errors during the runtime, we use exception handling technique in java program.
Let’s take different kinds of example programs to understand better. In this program, we will divide an integer number by zero. Java compiler cannot detect it.
Program source code 5:
public class DivisionByZeroError { public static void main(String[] args) { int a = 20, b = 5, c = 5; int z = a/(b-c); // Division by zero. System.out.println("Result: " +z); } }
Output: Exception in thread "main" java.lang.ArithmeticException: / by zero at errorsProgram.DivisionByZeroError.main(DivisionByZeroError.java:8)
The above program is syntactically correct. There is no syntax error and therefore, does not cause any problem during compilation. While executing, runtime error occurred that is not detected by compiler.
The error is detected by JVM only in runtime. Default exception handler displays an error message and terminates the program abnormally without executing further statements in the program.
Let’s take an example program where we will try to retrieve a value from an array using an index that is out of range of the array.
Program source code 6:
public class AccessingValueOutOfRangeError { public static void main(String[ ] args) { int arr[ ] = {1, 2, 3, 4, 5}; // Here, array size is 5. System.out.println("Value at 5th position: "+arr[5]); } }
Output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at errorsProgram.AccessingValueOutOfRangeError.main(AccessingValueOutOfRangeError.java:9)
Logical Errors in Java Program
Logical errors in Java are the most critical errors in a program and they are difficult to detect. These errors occur when the programmer uses incorrect logic or wrong formula in the coding.
The program will be compiled and executed successfully but does not return the expected output.
Logical errors are not detected either by Java compiler or JVM (Java runtime system). The programmer is entirely responsible for them. They can be detected by application testers when they compare the actual result with its expected result.
For example, a programmer wants to print even numbers from an array but he uses division (/) operator instead of modulus (%) operator to get the remainder of each number. Due to which he got the wrong results.
Let’s see the following source code related to this problem.
Program source code 7:
public class LogicalErrorEx { public static void main(String[] args) { int a[]={1, 2 , 5, 6, 3, 10, 12, 13, 14}; System.out.println("Even Numbers:"); for(int i = 0; i <a.length; i++) { if(a[i] / 2 == 0) // Using wrong operator. { System.out.println(a[i]); } } } }
Output: Even Numbers: 1
As you can see the program is successfully compiled and executed but the programmer got the wrong output due to logical errors in the program.
Seldom does a program run successfully at its first attempt. A software engineer in a company also commits several errors while designing the project or developing code.
These errors in a program are also called bugs and the process of fixing these bugs is called debugging.
All modern integrated development environments (IDEs) such as Eclipse, NetBeans, JBuilder, etc provide a tool known as debugger that helps to run the program step by step to detect bugs.
If you need professional help with Java homework assignments online, please address experts from AssignmentCore to get your Java projects done with no errors.
In this tutorial, we have familiarized different types of errors in java that may possibly occur in a program.
Thanks for reading!!!
Next ⇒ Exception handling Interview Programs for Practice
⇐ Prev Next ⇒
Error is an illegal operation performed by the user which results in the abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed before compiling and executing.
The most common errors can be broadly classified as follows:
1. Run Time Error:
Run Time errors occur or we can say, are detected during the execution of the program. Sometimes these are discovered when the user enters an invalid data or data which is not relevant. Runtime errors occur when a program does not contain any syntax errors but asks the computer to do something that the computer is unable to reliably do. During compilation, the compiler has no technique to detect these kinds of errors. It is the JVM (Java Virtual Machine) that detects it while the program is running. To handle the error during the run time we can put our error code inside the try block and catch the error inside the catch block.
For example: if the user inputs a data of string format when the computer is expecting an integer, there will be a runtime error. Example 1: Runtime Error caused by dividing by zero
Java
class
DivByZero {
public
static
void
main(String args[])
{
int
var1 =
15
;
int
var2 =
5
;
int
var3 =
0
;
int
ans1 = var1 / var2;
int
ans2 = var1 / var3;
System.out.println(
"Division of va1"
+ " by var2 is: "
+ ans1);
System.out.println(
"Division of va1"
+ " by var3 is: "
+ ans2);
}
}
Runtime Error in java code:
Exception in thread "main" java.lang.ArithmeticException: / by zero at DivByZero.main(File.java:14)
Example 2: Runtime Error caused by Assigning/Retrieving Value from an array using an index which is greater than the size of the array
Java
class
RTErrorDemo {
public
static
void
main(String args[])
{
int
arr[] =
new
int
[
5
];
arr[
9
] =
250
;
System.out.println("Value assigned! ");
}
}
RunTime Error in java code:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 at RTErrorDemo.main(File.java:10)
2. Compile Time Error:
Compile Time Errors are those errors which prevent the code from running because of an incorrect syntax such as a missing semicolon at the end of a statement or a missing bracket, class not found, etc. These errors are detected by the java compiler and an error message is displayed on the screen while compiling. Compile Time Errors are sometimes also referred to as Syntax errors. These kind of errors are easy to spot and rectify because the java compiler finds them for you. The compiler will tell you which piece of code in the program got in trouble and its best guess as to what you did wrong. Usually, the compiler indicates the exact line where the error is, or sometimes the line just before it, however, if the problem is with incorrectly nested braces, the actual error may be at the beginning of the block. In effect, syntax errors represent grammatical errors in the use of the programming language.
Example 1: Misspelled variable name or method names
Java
class
MisspelledVar {
public
static
void
main(String args[])
{
int
a =
40
, b =
60
;
int
Sum = a + b;
System.out.println(
"Sum of variables is "
+ sum);
}
}
Compilation Error in java code:
prog.java:14: error: cannot find symbol + sum); ^ symbol: variable sum location: class MisspelledVar 1 error
Example 2: Missing semicolons
Java
class
PrintingSentence {
public
static
void
main(String args[])
{
String s = "GeeksforGeeks";
System.out.println("Welcome to " + s)
}
}
Compilation Error in java code:
prog.java:8: error: ';' expected System.out.println("Welcome to " + s) ^ 1 error
Example: Missing parenthesis, square brackets, or curly braces
Java
class
MissingParenthesis {
public
static
void
main(String args[])
{
System.out.println("Printing
1
to
5
n");
int
i;
for
(i =
1
; i <=
5
; i++ {
System.out.println(i + "n");
}
}
}
Compilation Error in java code:
prog.java:10: error: ')' expected for (i = 1; i <= 5; i++ { ^ 1 error
Example: Incorrect format of selection statements or loops
Java
class
IncorrectLoop {
public
static
void
main(String args[])
{
System.out.println("Multiplication Table of
7
");
int
a =
7
, ans;
int
i;
for
(i =
1
, i <=
10
; i++) {
ans = a * i;
System.out.println(ans + "n");
}
}
}
Compilation Error in java code:
prog.java:12: error: not a statement for (i = 1, i <= 10; i++) { ^ prog.java:12: error: ';' expected for (i = 1, i <= 10; i++) { ^ 2 errors
Logical Error: A logic error is when your program compiles and executes, but does the wrong thing or returns an incorrect result or no output when it should be returning an output. These errors are detected neither by the compiler nor by JVM. The Java system has no idea what your program is supposed to do, so it provides no additional information to help you find the error. Logical errors are also called Semantic Errors. These errors are caused due to an incorrect idea or concept used by a programmer while coding. Syntax errors are grammatical errors whereas, logical errors are errors arising out of an incorrect meaning. For example, if a programmer accidentally adds two variables when he or she meant to divide them, the program will give no error and will execute successfully but with an incorrect result.
Example: Accidentally using an incorrect operator on the variables to perform an operation (Using ‘/’ operator to get the modulus instead using ‘%’)
Java
public
class
LErrorDemo {
public
static
void
main(String[] args)
{
int
num =
789
;
int
reversednum =
0
;
int
remainder;
while
(num !=
0
) {
remainder = num /
10
;
reversednum
= reversednum *
10
+ remainder;
num /=
10
;
}
System.out.println("Reversed number is "
+ reversednum);
}
}
Output:
Reversed number is 7870
Example: Displaying the wrong message
Java
class
IncorrectMessage {
public
static
void
main(String args[])
{
int
a =
2
, b =
8
, c =
6
;
System.out.println(
"Finding the largest number n");
if
(a > b && a > c)
System.out.println(
a + " is the largest Number");
else
if
(b > a && b > c)
System.out.println(
b + " is the smallest Number");
else
System.out.println(
c + " is the largest Number");
}
}
Output:
Finding the largest number 8 is the smallest Number
Syntax Error:
Syntax and Logical errors are faced by Programmers.
Spelling or grammatical mistakes are syntax errors, for example, using an uninitialized variable, using an undefined variable, etc., missing a semicolon, etc.
int x, y; x = 10 // missing semicolon (;) z = x + y; // z is undefined, y in uninitialized.
Syntax errors can be removed with the help of the compiler.
Errors
tutorial
java
- Compiler Errors
- Runtime Errors
- Stack Traces
- Catching Exceptions
- Checked Exceptions
- Logic Errors
- Debugging
- General Tips
- Homework
By now, you’ve probably seen a few errors, either when compiling or running your code. They can be frustrating, but they can also give you a lot of information about exactly how you can fix the problems in your code. This tutorial covers the types of errors you’ll see when programming in Java, and how to fix them.
Compiler Errors
Remember that the compiler converts from Java code (which humans can read) to Java byte code (which computers can read). The Java compiler is a lot like a translater. Now imagine that you told a translator to translate “flibberflabby” from English to Spanish. The translator would tell you that “flibberflabby” isn’t a word, so it can’t be translated!
That’s what happens when you write code that the compiler doesn’t understand. It doesn’t know how to translate your code into Java byte code, so it gives you an error. The rules of a language are called its syntax. Compiler errors are also called syntax errors, because it means that your code broke the rules of the langauge.
Compiler errors can be for things like forgotten semicolons or misspelled variables, but they can also be for violating the rules of Java, like using a non-static variable from a static function.
Here’s an example that contains a syntax error. Can you spot it?
class BadExample(){
public static void main(String[] args){
System.out.println("Happy Coding!");
}
}
Do you see the syntax error? Try to compile this code. Save it to a file named BadExample.java
, and then open a command prompt to the directory that contains that file, then type javac BadExample.java
and press enter.
The compiler will show you this error:
> javac BadExample.java
BadExample.java:1: error: '{' expected
class BadExample(){
^
1 error
This might seem like gibberish, but there’s a ton of information packed in here:
- The
BadExample.java
part tells you which class contains the error. This is useful if you’re compiling multiple classes. - The
:1
part tells you which line of code has the error. In this case, the first line of code contains an error. Note that sometimes an error can impact multiple lines, so if you can’t spot an error, try looking at the lines just before the reported error. - The
error: '{' expected
tells you why the compiler can’t translate your code. In this case, it’s saying that it expected a curly bracket{
character. - The
^
points to exactly where in the line of code the error was found. In this case, it’s pointing to the opening parenthesis(
character.
So, this error is telling us that the compiler thought it would see a curly bracket {
, but it saw a parenthesis (
instead. This is a violation of the syntax for creating a class, which shouldn’t have ()
parentheses in the class declaration!
Now we know enough to fix our code:
class BadExample{
public static void main(String[] args){
System.out.println("Happy Coding!");
}
}
Notice that we got rid of the parentheses ()
in the first line. This code will compile and run just fine.
It’s also possible to have more than one compiler error at a time. When this happens, always start with the first error. Fix that, and then try to compile again. Sometimes one syntax error can lead to multiple compiler errors. You should also make sure that you’ve split your problem up and you’re working on one small step. You don’t want to write 100 lines of code before compiling. Write a couple lines of code at a time, and compile as often as possible so you find errors as soon as you make them.
Runtime Errors
Even if you don’t get any compiler errors and the compiler translates your .java
file into a .class
file that you can run, your code still might contain other errors that the compiler can’t detect. Here’s an example:
public class ArgsPrinter{
public static void main(String[] args){
System.out.println(args[99]);
}
}
This code prints the 100th argument from the args
array (remember arrays are 0 based, so index 99 is the 100th index). It will compile fine, because the compiler has no way of knowing how many arguments you’re going to give your program until you actually run it.
But what happens if you run it but only give it 3 arguments?
> java ArgsPrinter
>java ArgsPrinter one two three
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 99
at ArgsPrinter.main(ArgsPrinter.java:3)
You get a runtime error, which means that even though your code “looks” okay, it did something bad when it actually ran. Let’s look at the error message in more detail:
- The
Exception in thread "main"
part tells us that we got a runtime error. - The
java.lang.ArrayIndexOutOfBoundsException
part tells you what type of error occurred. This is a class name that you can look up in the Java API. In this case, we’re getting anArrayIndexOutOfBoundsException
, which the Java API tells us means that “the index is either negative or greater than or equal to the size of the array.” - The
99
part gives you more information about the error. In this case it’s telling us that we tried to access the 99th index of an array. - The
at ArgsPrinter.main(ArgsPrinter.java:3)
part is called a stack trace, and it tells us which class, function, and line number the error occured on. In this case, the error occured on line3
of theArgsPrinter
class, inside themain()
function.
In this case the error was caused by accessing an index that the array didn’t have. We only gave the program 3 arguments, so the index only had 3 indexes. Then we tried to access index 99, which caused an error.
Stack Traces
Let’s look at another example that throws a runtime exception. Can you spot the error before running the code?
import java.util.ArrayList;
public class RuntimeErrorExample{
private ArrayList<String> list = new ArrayList<String>();
public void printLastThing(){
int lastIndex = list.size() - 1;
String thing = list.get(lastIndex);
System.out.println(thing);
}
public static void main(String[] args){
RuntimeErrorExample example = new RuntimeErrorExample();
example.printLastThing();
}
}
This code defines a RuntimeErrorExample
class that contains one ArrayList
variable named list
. It also defines a function named printLastThing()
that prints the last item in the ArrayList
. The logic is correct: like arrays, ArrayList
objects are 0 based, so if an ArrayList
contains 5 items, the last item is at index 4. So getting its size and subtrating 1 will give us the last index.
The main()
function then creates an instance of the class and calls the printLastThing()
function. But when we run it, we get this runtime error:
>java RuntimeErrorExample
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(ArrayList.java:418)
at java.util.ArrayList.get(ArrayList.java:431)
at RuntimeErrorExample.printLastThing(RuntimeErrorExample.java:9)
at RuntimeErrorExample.main(RuntimeErrorExample.java:15)
We’re getting an ArrayIndexOutOfBoundsException
just like before, and we can see that we’re trying to access index -1
, which causes an error because the index can’t be negative.
Notice that the stack trace now contains 4 lines. You might see that the error is actually happening inside the ArrayList
class. Before you assume you found a bug in the ArrayList
class, let’s take a closer look at the rest of the stack trace!
The stack trace shows you the sequence of events that lead to to the error happening. To make sense of a stack trace, read it from the bottom to the top:
at RuntimeErrorExample.main(RuntimeErrorExample.java:15)
: This tells us that the code started out in themain()
function, and that it got to line15
before calling another function.at RuntimeErrorExample.printLastThing(RuntimeErrorExample.java:9)
: Then themain()
function called theprintLastThing()
function. TheprintLastThing()
function got to line9
of theRuntimeErrorExample
class before calling another function.at java.util.ArrayList.get(ArrayList.java:431)
: TheprintLastThing()
function then called theget()
function in theArrayList
class. Inside theArrayList
class, theget()
function got to line 431 before calling another function.at java.util.ArrayList.elementData(ArrayList.java:418)
: Finally, line 418 of theArrayList
class, inside theelementData()
function, the error actually happens.
So, even though the error is coming from inside the ArrayList
class, we can use the stack trace to work backwards and find out where in our code the cause of the error came from.
In this example, the error is happening because we never actually add anything to the ArrayList
, so its size is 0
. Then we subtract 1
, which gives us -1
, and we use that as an index. That causes the error.
Catching Exceptions
We could prevent the ArrayIndexOutOfBoundsException
by using an if
statement that checks to make sure the index is valid before using it. Or we could use the isEmpty()
function that ArrayList
gives us:
import java.util.ArrayList;
public class RuntimeErrorExample{
private ArrayList<String> list = new ArrayList<String>();
public void printLastThing(){
if(list.isEmpty()){
System.out.println("You forgot to add something to the ArrayList.");
}
else{
int lastIndex = list.size() - 1;
String thing = list.get(lastIndex);
System.out.println(thing);
}
}
public static void main(String[] args){
RuntimeErrorExample example = new RuntimeErrorExample();
example.printLastThing();
}
}
Now when we call the printLastThing()
function, we first check if the list is empty, and print a friendly message if it is. Then only if it’s not empty, we get the last index and print out the last item.
It’s always a good idea to idiot-proof your code like this.
Another way to protect your code from exceptions is using try
and catch
blocks. You put code that might cause an error inside a try
block, and you put code you want to happen in case of an error inside a catch
block. It looks like this:
try{
//dangerous code here
}
//exception that might happen here
catch(Exception e){
//code you want to run when an error happens
}
Here’s the above example again, using a try
and catch
block instead of an if
statement:
import java.util.ArrayList;
public class RuntimeErrorExample{
private ArrayList<String> list = new ArrayList<String>();
public void printLastThing(){
try{
int lastIndex = list.size() - 1;
//this line throws an exception
String thing = list.get(lastIndex);
//this line won't be called!
System.out.println(thing);
}
catch(ArrayIndexOutOfBoundsException e){
//the program "shortcuts" to this code when an exception happens
System.out.println("You forgot to add something to the ArrayList.");
}
}
public static void main(String[] args){
RuntimeErrorExample example = new RuntimeErrorExample();
example.printLastThing();
}
}
Now, when the String thing = list.get(lastIndex);
line causes an ArrayIndexOutOfBoundsException
, the program automatically jumps to the code inside the catch
block. This means that the System.out.println(thing);
line is not run. Instead, the code inside the catch
block is run instead.
Also note that the code inside the catch
block is only run when an exception is thrown. If no exception is thrown, then the code inside the catch
block is skipped.
Also note that the catch
block is given an instance of a class representing the error that occurred. You should check the Java API for useful function, but one you’ll use all the time is printStackTrace()
:
catch(ArrayIndexOutOfBoundsException e){
System.out.println("You forgot to add something to the ArrayList.");
e.printStackTrace();
}
This lets you add a friendly error message, but still prints the stack trace to the console so you can figure out exactly what caused the error.
Checked Exceptions
In the above code, note that we could use a try
and catch
block, but we didn’t have to. That’s because ArrayIndexOutOfBoundsException
is an unchecked exception. If a function might throw an unchecked exception, you don’t have to do anything special.
However, functions can also throw checked exceptions, which you do have to catch. Look at this program:
import java.io.PrintWriter;
public class FileMaker{
public static void main(String[] args){
PrintWriter output = new PrintWriter("OutputFile.txt");
output.write("Happy Coding!");
output.close();
}
}
This code uses the PrintWriter
class to create a file named OutputFile.txt
. First, we create an instance of PrintWriter
and give it the name of a file to create. Then we write the contents of the file, and finally we call the close()
function to free the file up (otherwise we might get errors when we try to open the file in a text editor). As always, you should check out the Java API to learn more about new classes.
But if you try to compile this code, you’ll get an error:
> javac FileMaker.java
FileMaker.java:6: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
PrintWriter output = new PrintWriter("OutputFile.txt");
^
1 error
This error tells us that the PrintWriter output = new PrintWriter("OutputFile.txt");
line of code can give us a FileNotFoundException
, so we have to use a try
and catch
block with this code. That’s because FileNotFoundException
is a checked exception, so we have to specifically catch possible errors.
So, we can put our code inside a try
block, and we add a catch
block that catches the FileNotFoundException
. We just call the printStackTrace()
function so we can debug the error if it ever happens.
import java.io.PrintWriter;
import java.io.FileNotFoundException;
public class FileMaker{
public static void main(String[] args){
try{
PrintWriter output = new PrintWriter("OutputFile.txt");
output.write("Happy Coding!");
output.close();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
}
Now we’re specifically catching the FileNotFoundException
, so the compiler is happy and our code is safe.
Note: Never leave a catch
block empty! You’ll have no way to know that anything went wrong, which makes it very hard to debug your code when something does go wrong. And you’ve probably learned by now that things do go wrong all the time when you’re programming! So at least put a call to printStackTrace()
inside a catch
block, even if you don’t think the exception will ever actually happen.
Logic Errors
Sometimes you’ll write code that compiles, and doesn’t throw any runtime exceptions, but still doesn’t work how you expected it to. This is almost always caused by a logic error, and it’s usually a result of the programmer (that’s you!) making an assumption or a typo.
Let’s look at this program:
public class ArrayCounter{
public static int countArray(int[] array){
int total = 0;
for(int i = 1; i < array.length; i++){
total += array[i];
}
return total;
}
public static void main(String[] args){
int[] array = {1, 2, 3};
int total = countArray(array);
System.out.println("The total is: " + total);
}
}
This program creates a countArray()
function that takes an int[]
array parameter. It loops over the array and adds every number to the total, which it then returns. Then the main()
function creates an array, calls the countArray()
function with it, and then prints out the resulting total.
If you compile and run this program, you’ll see that it prints out The total is: 5
, even though the total should be 6! Can you spot the problem?
The problem is this line of code:
for(int i = 1; i < array.length; i++){
Remember that arrays are 0-based, so the first index is always 0, not 1. So this loop actually starts at the second index, and it skips the first number! To fix the logic error, we need to make the loop start at 0:
for(int i = 0; i < array.length; i++){
But even if we fix that error, things can still be wrong. Try compiling and running this:
public class ArrayCounter{
public static int countArray(int[] array){
int total = 0;
for(int i = 0; i < array.length; i++){
total += array[i];
}
return total;
}
public static void main(String[] args){
int oneBillion = 1000000000;
int[] array = {oneBillion, oneBillion, oneBillion};
int total = countArray(array);
System.out.println("The total is: " + total);
}
}
You might expect this to print out 3 billion, but it actually prints out a negative number! What’s going on?
Remember that the different number types (like int
and double
) hold different types of numbers. The int
type holds whole numbers, but they have to be between -2,147,483,648
and 2,147,483,647
. This is because the number is stored in a 32-digit binary number, but you don’t really have to understand that part. The point is that when we try to hold 3 billion in an int
value, the number goes over the limit and starts back over at the beginning, which is a negative number. That’s why we get a negative number instead of 3 billion.
To fix this error, we could use a long
variable, which can hold larger values. For more info on data types in Java, check out the Java documentation.
The lesson is that even if you write code that compiles and runs without any exceptions, it still might contain logic errors. This doesn’t mean you’re a bad programmer! They happen all the time to every single one of us.
Debugging
When you encounter a runtime exception or a logic error, that means it’s time to debug your program. You need to figure out exactly what’s going on in your code, and exactly what in the code is behaving differently from what you expected.
One of the easiest ways to do that is by adding System.out.println()
statements to your code. This can help you figure out the values of variables, which functions are being called in what order, how many times a loop is iterating, etc.
Let’s say we have a goal of writing a function that takes a String
direction as a parameter, and returns the direction after rotating 90 degrees. We might write this program:
public class DirectionRotater{
public static String rotate(String direction){
if(direction.equals("up")){
direction = "right";
}
if(direction.equals("right")){
direction = "down";
}
if(direction.equals("down")){
direction = "left";
}
if(direction.equals("left")){
direction = "up";
}
return direction;
}
public static void main(String[] args){
String direction = "up";
direction = rotate(direction);
direction = rotate(direction);
System.out.println("Direction: " + direction);
}
}
This program creates a rotate()
function that takes a String
parameter. Depending on the value of that parameter, the function reassigns the variable to be a rotated direction: up turns into right, right turns into down, down turns into left, and left turns into up. If this doesn’t make sense, look at the arrow keys on your keyboard, and imagine rotating each key by 90 degrees. Then the function just returns the value.
The main()
function then creates a direction
variable with a value of "up"
. The code passes that into the rotate()
function, and then reassigns the direction
variable to the value returned from that function. It does this twice, so we’d expect the printed direction to be down
. But instead, we see that the direction is up!
> java DirectionRotater
Direction: up
(In fact, no matter what direction we pass into the rotate()
function, it always returns "up"
!)
To figure out what’s going on, we need to read through the program and make sure each line of code is doing what we expect it to. Try reading through the code in your head first, trying to figure out exactly what each line does. Use a piece of paper to jot down variable values.
If you still can’t figure it out, then you should add print statements to your program. Add as many as it takes to figure out exactly what the code is doing.
public class DirectionRotater{
public static String rotate(String direction){
System.out.println("rotate function got param: " + direction);
if(direction.equals("up")){
System.out.println("Entered first if statement.");
direction = "right";
System.out.println("Direction is now: " + direction);
}
if(direction.equals("right")){
System.out.println("Entered second if statement.");
direction = "down";
System.out.println("Direction is now: " + direction);
}
if(direction.equals("down")){
System.out.println("Entered third if statement.");
direction = "left";
System.out.println("Direction is now: " + direction);
}
if(direction.equals("left")){
System.out.println("Entered fourth if statement.");
direction = "up";
System.out.println("Direction is now: " + direction);
}
System.out.println("Returning: " + direction);
return direction;
}
public static void main(String[] args){
String direction = "up";
System.out.println("Direction starts as: " + direction);
direction = rotate(direction);
System.out.println("Rotated once. Direction is now: " + direction);
direction = rotate(direction);
System.out.println("Rotated twice. Direction is now: " + direction);
System.out.println("Direction: " + direction);
}
}
We’re using System.out.println()
to figure out exactly which functions are being called, which if
statements are being entered, and the value of variables. Now when we run the code, we see this:
> java DirectionRotater
Direction starts as: up
rotate function got param: up
Entered first if statement.
Direction is now: right
Entered second if statement.
Direction is now: down
Entered third if statement.
Direction is now: left
Entered fourth if statement.
Direction is now: up
Returning: up
Rotated once. Direction is now: up
rotate function got param: up
Entered first if statement.
Direction is now: right
Entered second if statement.
Direction is now: down
Entered third if statement.
Direction is now: left
Entered fourth if statement.
Direction is now: up
Returning: up
Rotated twice. Direction is now: up
Direction: up
Now if we step through the code while reading these print statements, we can see that the rotate()
function is getting the correct parameter, but for some reason it’s entering every single if
statement instead of just one of them.
This is because we forgot the else
part of our if
statements! So the rotate()
function reaches the first if
statement, which it enters because direction
starts out as "up"
. It reassigns direction
to be "right
”, which is correct so far. But then it looks at the next if
statement, which checks whether direction
is "right"
! It is, so it reassigns it to be "down"
. This process repeats for all of the if
statements, until the last one reassigns direction
to be "up"
.
To fix this, we need to use else if
statements:
if(direction.equals("up")){
direction = "right";
}
else if(direction.equals("right")){
direction = "down";
}
else if(direction.equals("down")){
direction = "left";
}
else if(direction.equals("left")){
direction = "up";
}
Now when one of the if
statements is entered, it doesn’t evaluate any of the other if
statements. This causes the direction to be rotated only once, which was our original goal!
Let’s look at another example. Let’s say we have a goal of creating a class that represents a line segment. It should hold two Point
objects and contain a getLength()
function that returns the distance between those points. We might write this code:
import java.awt.Point;
public class LineSegment{
private Point startPoint;
private Point endPoint;
public LineSegment(Point startPoint, Point endPoint){
startPoint = startPoint;
endPoint = endPoint;
}
public double getLength(){
double distance = Math.sqrt(Math.pow(endPoint.getX() - startPoint.getX(), 2) + Math.pow(endPoint.getY() - startPoint.getY(), 2));
return distance;
}
public static void main(String[] args){
Point pointOne = new Point(1, 2);
Point pointTwo = new Point(100, 200);
LineSegment line = new LineSegment(pointOne, pointTwo);
System.out.println("Length: " + line.getLength());
}
}
This class contains two instances of the Point
class (as always, you should check out the Java API whenever you see a class you haven’t seen before) and uses the distance formula to find the length of the line segment.
However, if you run the code you’ll see that the code hits a NullPointerException
:
> java LineSegment
Exception in thread "main" java.lang.NullPointerException
at LineSegment.getLength(LineSegment.java:14)
at LineSegment.main(LineSegment.java:22)
NullPointerException
is probably the most common runtime error, and it means that your code uses a variable that doesn’t have a value. You can debug a NullPointerException
exactly like any other error: by stepping through the code and understanding exactly what each line does, and by adding print statements that help you understand exactly what’s happening.
For example, the stack trace tells us that the error is happening on this line:
double distance = Math.sqrt(Math.pow(endPoint.getX() - startPoint.getX(), 2) + Math.pow(endPoint.getY() - startPoint.getY(), 2));
return distance;
Which means that one of the variables on that line doesn’t have a value. More specifically, the value is null
. To figure out exactly which variable is null
, we can print out their values just before the line that hits the exception:
public double getLength(){
System.out.println("startPoint: " + startPoint);
System.out.println("endPoint: " + endPoint);
double distance = Math.sqrt(Math.pow(endPoint.getX() - startPoint.getX(), 2) + Math.pow(endPoint.getY() - startPoint.getY(), 2));
return distance;
}
When we run that code, we can see that both startPoint
and endPoint
are null
!
> java LineSegment
startPoint: null
endPoint: null
Exception in thread "main" java.lang.NullPointerException
at LineSegment.getLength(LineSegment.java:16)
at LineSegment.main(LineSegment.java:24)
So now we have to work backwards and find out why those values are null
. We could add more print statements:
import java.awt.Point;
public class LineSegment{
private Point startPoint;
private Point endPoint;
public LineSegment(Point startPoint, Point endPoint){
System.out.println("in constructor, parameter startPoint: " + startPoint);
System.out.println("in constructor, parameter endPoint: " + endPoint);
startPoint = startPoint;
endPoint = endPoint;
System.out.println("in constructor, this.startPoint: " + this.startPoint);
System.out.println("in constructor, this.endPoint: " + this.endPoint);
}
public double getLength(){
System.out.println("startPoint: " + startPoint);
System.out.println("endPoint: " + endPoint);
double distance = Math.sqrt(Math.pow(endPoint.getX() - startPoint.getX(), 2) + Math.pow(endPoint.getY() - startPoint.getY(), 2));
return distance;
}
public static void main(String[] args){
Point pointOne = new Point(1, 2);
Point pointTwo = new Point(100, 200);
System.out.println("in main, pointOne: " + pointOne);
System.out.println("in main, pointTwo: " + pointTwo);
LineSegment line = new LineSegment(pointOne, pointTwo);
System.out.println("Length: " + line.getLength());
}
}
Then we can run that code to get the output:
> java LineSegment
in main, pointOne: java.awt.Point[x=1,y=2]
in main, pointTwo: java.awt.Point[x=100,y=200]
in constructor, parameter startPoint: java.awt.Point[x=1,y=2]
in constructor, parameter endPoint: java.awt.Point[x=100,y=200]
in constructor, this.startPoint: null
in constructor, this.endPoint: null
startPoint: null
endPoint: null
Exception in thread "main" java.lang.NullPointerException
at LineSegment.getLength(LineSegment.java:22)
at LineSegment.main(LineSegment.java:34)
Now you can use the output to help you trace through the code in your head. You can see that the points have values inside the main()
function, and the parameters are passed correctly. But then the class-level variables aren’t set, which is why they’re null
when we call the getLength()
function. So something is wrong with how we’re setting the class-level variables using the parameter variables:
startPoint = startPoint;
endPoint = endPoint;
Now that you have the problem narrowed down to just a couple lines, you can go back and read the tutorials for what those lines are doing. In this case, we’re creating a class. You might read through that and realize that we needed to use the this
keyword to reference the class-level variables! Without that, these lines are just assigning the parameters back to themselves, which doesn’t change anything. We needed to do this:
this.startPoint = startPoint;
this.endPoint = endPoint;
Now our code sets the class-level variables to the values of the parameters. Now our code works fine!
> java LineSegment
Length: 221.37072977247917
If you still can’t figure it out after debugging, adding print statements, and narrowing it down to just a few lines that aren’t behaving correctly, then you can get help by posting in the forum!
General Tips
Debugging can be frustrating, but it’s a huge part of being a programmer. Here are a couple tips to keep yourself sane:
- Blame yourself first. It can be tempting to assume you found a bug in Java, or in the library you’re using. And while it’s not impossible that you found a bug, it’s much more likely that it’s a bug in your code. So you should ask yourself “what am I doing wrong?” and “which of my assumptions is incorrect?” instead of blaming the code.
- Don’t take it personally. Those questions don’t mean that you’re a bad programmer. Bugs happen to every single programmer, every single time they sit down to write code. So try not to get frustrated, especially when people ask you to narrow your problem down or debug your program. Just go through the process we just talked about: run through your code in your head, and use print statements to figure out what’s going on.
- Work in small chunks. Don’t try to write your program all at one time. You should be recompiling as often as possible- after every line if you can. Test single methods by themselves with hard-coded values, and make sure it’s doing exactly what you expected before you move on to the next step. That will also make it easier to get help when you do get stuck!
If all else fails, sometimes the best thing you can do is take a break. Go on a walk, pet your cat, and try to clear your head. You’ll be amazed at how many solutions you end up thinking of in the shower.
Homework
- Write a program that outputs 100 random points to a text file. Write another program that reads in those points and prints out the center of all those points.
As the name implies, runtime errors occur during the execution of a software program. They occur when an application runs. Any time an application behaves in a way that negatively deviates from its established requirements, this means a runtime error has occurred.
Such a broad definition isn’t very helpful when Java runtime errors stop your app in its tracks. Let’s take a closer look at the five most common runtime errors in Java programmers will encounter, and the steps and strategies to pursue to address them.
Top 5 runtime errors in Java
The most common runtime errors in Java can be broken into the following five categories:
- Data entry errors
- Insufficient runtime resources
- Poorly implemented logic
- External resource changes
- Third-party vulnerabilities
Input sanitization failures
There are innumerable ways user input can corrupt an application.
On an HTML-based comment board, a user who is allowed to innocently submit an unencoded less than (<) or greater than sign (>) has the potential to completely ruin the ability of that webpage to render. Similarly, text-processing systems built to expect all input in ASCII format can prematurely terminate if they receive emojis or nonstandard character inputs.
More nefariously, a favorite attack vector of hackers is SQL injection, which hides a harmful executable database query inside an otherwise innocuous input field. This not only can cause an application to fail, but potentially surrender control of the entire data layer.
The process of input sanitization, or data scrubbing, converts the broad spectrum of data that could potentially be entered into applications into a safe range of values that a program comprehends. Use of such libraries helps mitigate runtime errors caused by input sanitization failures.
Popular Java frameworks such as Apache BVal and Hibernate Validator perform simple, annotation-based input cleansing, and they integrate easily into any Java-based application.
Insufficient runtime resources
Software developers don’t shoulder the blame for every type of runtime error that occurs. Many runtime errors in Java involve resource limitations caused by problems with the underlying infrastructure. Examples include: network timeouts, out of memory conditions, CPU overutilization or an inability to schedule a thread on the processor.
One way to avoid resource-related runtime errors is to use a load testing tool, such as JMeter or LoadRunner, in an application’s CI/CD pipeline. If these tools detect a possible performance problem, they can stop the application before it moves further down the pipeline toward production deployment.
Some applications’ load varies drastically. For example, a financial services app may see steady load most of the time but be extremely busy at the end of trading day. A tax service might hit a peak load before the filing deadline but have relatively little load the rest of the year.
DevOps teams must monitor their performance metrics with tools to preemptively detect and mitigate resource-related runtime errors. Examples of such tools include JDK Flight Recorder and Java Mission Control.
For applications with completely unpredictable workloads, use cloud-based load balancing technology to allocate resources elastically. This eliminates both underallocated resources, and the trap of purchasing expensive, rarely used hardware.
Poorly implemented logic
Just because code compiles doesn’t mean it works properly. Code often contains logical problems that cause an application to fail at runtime.
Java contains a built-in construct to handle a class of common code-related runtime errors, called the RuntimeException, or the unchecked exception. Java 17 defines 78 such errors in the SDK alone, and other projects and frameworks additionally define their own RuntimeException errors.
The most commonly encountered RuntimeExceptions in Java include:
- ArithmeticException, for divide by zero errors;
- ClassCastException, for data type conversion errors;
- ConcurrentModificationException, for incorrectly implemented parallel computations;
- IndexOutOfBoundsException, when a nonexistent element in an array is accessed; and
- NullPointerException, when a method is invoked on a null object.
Developers are not required to handle unchecked exceptions in their code. But an unchecked exception that is thrown and ignored will terminate an application.
At the very least, every application should include a generic exception harness that can catch every possible RuntimeException, log the error and allow the problematic thread of execution to die rather than abort the entire application.
External resource configuration
Enterprise applications rarely exist in an isolated bubble. They typically interact with everything from NoSQL databases and relational systems to Kafka queues and RESTful APIs. Unfortunately, if your application is unable to connect to a required, external system, this inevitably results in a runtime error.
An external resource can precipitate a runtime error if any of the following situations occur with no corresponding update to the calling program:
- an IP address changes;
- credentials change;
- firewall configuration change; or
- the external system goes down for maintenance.
Applications should react nimbly when resources change. The 12-Factor App insists developers keep all configuration data external to the application so that applications can react nimbly when resources change. The ability to update property files without changing the codebase allows applications to deal with external resource changes, and avoids an application rebuild.
Relatedly, chaos engineering tools randomly terminate the processes upon which an application depends. Such tools force developers to write code that remains responsive and resilient even when external systems fail.
The inherent problem with external resources is that developers cannot control them — but they can control how an application responds when those external resources fail. Anticipate runtime errors generated by the systems you don’t control, and write applications that respond gracefully when those external systems fail.
Third-party library vulnerabilities
Any nontrivial enterprise application includes dozens of dependencies on third-party libraries to perform functions such as logging, monitoring, input validation, form handling and more.
Unfortunately, any bugs in a third-party library become a bug in the application you deploy. This became uncomfortably real for the Java world in December 2021, as an LDAP inject flaw in the widely used Log4j 2 library forced JVMs throughout the world to go offline.
One way to mitigate against the possibility that software dependencies introduce runtime errors into applications is to only use trusted libraries from organizations such as Apache or Eclipse.
Another protective measure is to regularly update an application’s dependencies to the latest version as soon as updates become available.
Finally, be aware of secondary or tertiary dependencies — ones that your primary dependencies themselves rely upon — and be aware of any risks those bring with them.
In the world of software development, «perfect» is the enemy of «done.» No program is immune from the threat of an unanticipated runtime error. However, when enterprise developers raise their awareness of the possible causes and take steps to mitigate against potential threats, they can create software that minimizes the probability of encountering a runtime error.
In one of my prof slides on ploymorphism, I see this piece of code with a couple of comments:
discountVariable = //will produce
(DiscountSale)saleVariable;//run-time error
discountVariable = saleVariable //will produce
//compiler error
As you can see, it says in the first casting statement that it’ll produce run-time error and in the other one it says it’ll produce compiler error.
What makes these errors? and how they differ from each other?
The Unfun Cat
28.9k29 gold badges110 silver badges150 bronze badges
asked Feb 27, 2012 at 20:31
3
A run time error will only occur when the code is actually running.
These are the most difficult — and lead to program crashes and bugs in your code which can be hard to track down.
An example might be trying to convert a string: «hello» into an integer:
string helloWorld = "hello";
int willThrowRuntimeError = Convert.ToInt32(helloWorld);
The compiler may not see this as a problem but when run an error will be thrown.
Compiler errors are due to inaccuracies in code, where the compiler throws an error to alert you to something which will not compile, and therefore cannot be run.
An example of a compiler error would be:
int = "this is not an int";
user
4,8906 gold badges17 silver badges35 bronze badges
answered Feb 27, 2012 at 20:38
DIXONJWDDDIXONJWDD
1,25610 silver badges20 bronze badges
1
A runtime error happens during the running of the program. A compiler error happens when you try to compile the code.
If you are unable to compile your code, that is a compiler error.
If you compile and run your code, but then it fails during execution, that is runtime.
answered Feb 27, 2012 at 20:33
James MontagneJames Montagne
76.8k14 gold badges108 silver badges129 bronze badges
2
Compile time errors refers to syntax and semantics. For example, if you do operations that involves different types. Ex: adding a string with an int, or dividing a string by a real. (read the last paragraph thou!!!)
Run Time errors are those that are detected when the program execute. For example, division by zero. The compiler can not know if the operation x/a-b will leads to division by zero until the execution.
This is a very broad explanation. There are many smart compilers, and, also, is possible to do internal casting among different types that leads to operations that make sense. It it possible to pre-compile code and see some run time errors even if the code is not executed.
Refer to this link too: Runtime vs Compile time
answered Feb 27, 2012 at 20:37
Compile time errors are errors of syntax and semantics.
Run time errors are errors of logic primarily. Due to something the programmer has overlooked, the program crashes e.g. division by 0, accessing a variable without initializing it first etc.
answered Jun 8, 2015 at 7:03
HadiHadi
5008 silver badges20 bronze badges
Compile Time error means that the Compiler knows that discountVariable = saleVariable
must be end with a semi colon as belowdiscountVariable = saleVariable;
so it will throw an error when you compile the code.
Run Time error means that the error will occur at run time, because even though you are casting saleVariable into discountVariable, the cast cannot take because they differ in type.
answered Feb 27, 2012 at 20:33
CodeBlueCodeBlue
14.5k32 gold badges94 silver badges131 bronze badges
think you’ve already got the general desc of what’s the difference. Specifically in the code you have shown in the OP,
- In second statement, compiler compares the types on LHS and RHS and finds no implicit cast possible so it gives the error.
- first statement is seen by compiler as the same, but here programmer explicitly casts the type, which is as good as telling compiler that I know what I’m doing and of course the compiler trusts you and gives you no errors.
answered Feb 27, 2012 at 20:50
KashyapKashyap
14.5k12 gold badges63 silver badges100 bronze badges
1
Its because the compiler doesn’t know the object type of «saleVariable» until that value has actually been set when the program is running.
Your are forcing whatever is in salesVariable into the type DiscountSale this is considered unsafe and cannot be evaluated until runtime.
answered Feb 27, 2012 at 20:33
bigamilbigamil
6574 silver badges12 bronze badges
2
Compilation/Compile time/Syntax/Semantic errors: Compilation or compile time errors are error occurred due to typing mistake, if we do not follow the proper syntax and semantics of any programming language then compile time errors are thrown by the compiler. They wont let your program to execute a single line until you remove all the syntax errors or until you debug the compile time errors.
Example: Missing a semicolon in C or mistyping int
as Int
.
Runtime errors: Runtime errors are the errors that are generated when the program is in running state. These types of errors will cause your program to behave unexpectedly or may even kill your program. They are often referred as Exceptions.
Example: Suppose you are reading a file that doesn’t exist, will result in a runtime error.
Read more about all programming errors here
answered May 25, 2015 at 5:37
If you’d use Google, you’d get this:
Compile time error is any type of error that prevent a java program compile like a syntax error, a class not found, a bad file name for the defined class, a possible loss of precision when you are mixing different java data types and so on.
A runtime error means an error which happens, while the program is running. To deal with this kind of errors java define Exceptions. Exceptions are objects represents an abnormal condition in the flow of the program. It can be either checked or unchecked.
http://wiki.answers.com/Q/Difference_between_run_time_error_and_compile_time_error_in_java
answered Feb 27, 2012 at 20:32
2
Compiler errors are due to inaccuracies in code, where the compiler throws an error to alert you to something which will not compile, and therefore cannot be run.
Ex :- MethodOverloading
class OverloadingTest {
void sum(int a, long b) {
System.out.println("a method invoked");
}
void sum(long a, int b) {
System.out.println("b method invoked");
}
public static void main(String args[]) {
OverloadingTest obj = new OverloadingTest();
obj.sum(200, 200);// now ambiguity
}
}
Run Time errors are those that are detected when the program execute. For example, division by zero. The compiler can not know if the operation x/a-b will leads to division by zero until the execution
answered Apr 21, 2015 at 8:48
Nikhil KumarNikhil Kumar
2,5083 gold badges19 silver badges24 bronze badges