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
Содержание
- Unchecked Exceptions The Controversy
- How to Solve the Most Common Runtime Errors in Java
- Runtime Errors vs Compile-Time Errors
- Runtime Errors vs Logical Errors
- What Causes Runtime Errors in Java
- Runtime Error Examples
- Division by zero error
- Accessing an out of range value in an array
- How to Solve Runtime Errors
- Track, Analyze and Manage Errors With Rollbar
- Полное руководство по обработке исключений в Java
- Обработка исключений в Java. Краткий обзор
- Что и как происходит, когда появляется ошибка
- Основные элементы обработки исключений в Java
- Иерархия исключений в Java
- Полезные методы в обработке исключений
- Автоматическое управление ресурсами и улучшения блока перехвата ошибок в Java 7
Unchecked Exceptions The Controversy
Because the Java programming language does not require methods to catch or to specify unchecked exceptions ( RuntimeException , Error , and their subclasses), programmers may be tempted to write code that throws only unchecked exceptions or to make all their exception subclasses inherit from RuntimeException . Both of these shortcuts allow programmers to write code without bothering with compiler errors and without bothering to specify or to catch any exceptions. Although this may seem convenient to the programmer, it sidesteps the intent of the catch or specify requirement and can cause problems for others using your classes.
Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope? Any Exception that can be thrown by a method is part of the method’s public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method’s programming interface as its parameters and return value.
The next question might be: «If it’s so good to document a method’s API, including the exceptions it can throw, why not specify runtime exceptions too?» Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program’s clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).
One case where it is common practice to throw a RuntimeException is when the user calls a method incorrectly. For example, a method can check if one of its arguments is incorrectly null . If an argument is null , the method might throw a NullPointerException , which is an unchecked exception.
Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don’t want to be bothered with specifying the exceptions your methods can throw.
Here’s the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
Источник
How to Solve the Most Common Runtime Errors in Java
Table of Contents
A runtime error in Java is an application error that occurs during the execution of a program. A runtime error occurs when a program is syntactically correct but contains an issue that is only detected during program execution. These issues cannot be caught at compile-time by the Java compiler and are only detected by the Java Virtual Machine (JVM) when the application is running.
Runtime errors are a category of exception that contains several more specific error types. Some of the most common types of runtime errors are:
- IO errors
- Division by zero errors
- Out of range errors
- Undefined object errors
Runtime Errors vs Compile-Time Errors
Compile-time errors occur when there are syntactical issues present in application code, for example, missing semicolons or parentheses, misspelled keywords or usage of undeclared variables.
These syntax errors are detected by the Java compiler at compile-time and an error message is displayed on the screen. The compiler prevents the code from being executed until the error is fixed. Therefore, these errors must be addressed by debugging before the program can be successfully run.
On the other hand, runtime errors occur during program execution (the interpretation phase), after compilation has taken place. Any code that throws a runtime error is therefore syntactically correct.
Runtime Errors vs Logical Errors
A runtime error could potentially be a legitimate issue in code, for example, incorrectly formatted input data or lack of resources (e.g. insufficient memory or disk space). When a runtime error occurs in Java, the compiler specifies the lines of code where the error is encountered. This information can be used to trace back where the problem originated.
On the other hand, a logical error is always the symptom of a bug in application code leading to incorrect output e.g. subtracting two variables instead of adding them. In case of a logical error, the program operates incorrectly but does not terminate abnormally. Each statement may need to be checked to identify a logical error, which makes it generally harder to debug than a runtime error.
What Causes Runtime Errors in Java
The most common causes of runtime errors in Java are:
- Dividing a number by zero.
- Accessing an element in an array that is out of range.
- Attempting to store an incompatible type value to a collection.
- Passing an invalid argument to a method.
- Attempting to convert an invalid string to a number.
- Insufficient space in memory for thread data.
When any such errors are encountered, the Java compiler generates an error message and terminates the program abnormally. Runtime errors don’t need to be explicitly caught and handled in code. However, it may be useful to catch them and continue program execution.
To handle a runtime error, the code can be placed within a try-catch block and the error can be caught inside the catch block.
Runtime Error Examples
Division by zero error
Here is an example of a java.lang.ArithmeticException , a type of runtime exception, thrown due to division by zero:
In this example, an integer a is attempted to be divided by another integer b , whose value is zero, leading to a java.lang.ArithmeticException :
Accessing an out of range value in an array
Here is an example of a java.lang.ArrayIndexOutOfBoundsException thrown due to an attempt to access an element in an array that is out of bounds:
In this example, an array is initialized with 5 elements. An element at position 5 is later attempted to be accessed in the array, which does not exist, leading to a java.lang.ArrayIndexOutOfBoundsException runtime error:
How to Solve Runtime Errors
Runtime errors can be handled in Java using try-catch blocks with the following steps:
- Surround the statements that can throw a runtime error in try-catch blocks.
- Catch the error.
- Depending on the requirements of the application, take necessary action. For example, log the exception with an appropriate message.
To illustrate this, the code in the earlier ArithmeticException example can be updated with the above steps:
Surrounding the code in try-catch blocks like the above allows the program to continue execution after the exception is encountered:
Runtime errors can be avoided where possible by paying attention to detail and making sure all statements in code are mathematically and logically correct.
Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing errors easier than ever. Try it today.
Источник
Полное руководство по обработке исключений в Java
Исключение — ошибка, которая нарушает нормальную работу программы. Java обеспечивает надежный объектно-ориентированный способ обработки исключений. Именно его мы и будем изучать в этом руководстве.
Обработка исключений в Java. Краткий обзор
Исключение может возникнуть в разного рода ситуациях: неправильные входные данные, аппаратный сбой, сбоя сетевого соединения, ошибка при работе с базой данных и т.д. Именно поэтому любой Java программист должен уметь правильно обрабатывать исключения, понимать причины их появления и следовать лучшим практикам работы с исключениями даже в небольших проектах.
Java — объектно-ориентированный язык программирования, поэтому всякий раз, когда происходит ошибка при выполнении инструкции, создается объект-исключение, а затем нормальный ход выполнения программы останавливается и JRE пытается найти кого-то, кто может справиться (обработать) это исключение. Объект-исключение содержит много информации об отладке, а именно номер строки, где произошло исключение, тип исключения и т.д.
Что и как происходит, когда появляется ошибка
Когда в методе происходит исключение, то процесс создания объекта-исключения и передачи его в Runtime Environment называется «бросать исключение».
После создания исключения, Java Runtime Environment пытается найти обработчик исключения.
Обработчик исключения — блок кода, который может обрабатывать объект-исключение.
Логика нахождения обработчика исключений проста — прежде всего начинается поиск в методе, где возникла ошибка, если соответствующий обработчик не найден, то происходит переход к тому методу, который вызывает этот метод и так далее.
У нас есть 3 метода, каждый из которых вызывает друг-друга: А -> В -> С (А вызывает В, а В вызывает С). Если исключение появляется в методе C, то поиск соответствующего обработчика будет происходить в обратном порядке: С -> В -> А (сначала там, где было исключение — в С, если там нет обработчика, то идем в метод В — если тут тоже нет, то идем в А).
Если соответствующий обработчик исключений будет найден, то объект-исключение передаётся обработчику.
Обработать исключение — значит «поймать исключение».
Если обработчик исключений не был найден, то программа завершает работу и печатает информации об исключении.
Обратите внимание, что обработка исключений в Java — это фреймворк, который используется только для обработки ошибок времени выполнения. Ошибки компиляции не обрабатываются рамках обработки исключений.
Основные элементы обработки исключений в Java
Мы используем определенные ключевые слова в для создания блока обработки исключений. Давайте рассмотрим их на примере. Также мы напишем простую программу для обработки исключений.
- Бросить исключение ( throw ) — ключевое слово, которое используется для того, чтобы бросить исключение во время выполнения. Мы знаем, что Java Runtime начинает поиск обработчика исключений как только оно будет брошено, но часто нам самим нужно генерировать исключение в нашем коде, например, в программе авторизации, если какое-то поле null . Именно для таких случаем и существует возможность бросить исключение.
- throws — когда мы бросаем исключение в методе и не обрабатываем его, то мы должны использовать ключевое слово throws в сигнатуре метода для того, чтобы пробросить исключение для обработки в другом методе. Вызывающий метод может обработать это исключение или пробросить его еще дальше с помощью throws в сигнатуре метода. Следует отметить, что пробрасывать можно сразу несколько исключений.
- Блок try-catch используется для обработки исключений в коде. Слово try — это начало блока обработки, catch — конец блока для обработки исключений. Мы можем использовать сразу несколько блоков catch при одном try . catch в качестве параметра принимает тип исключения для обработки.
- finally — необязательная завершающая конструкция блока try-catch . Как только исключение остановило процесс исполнения программы, в finally мы можем безопасно освободить какие-то открытые ресурсы. Следует отметить, что finally блок выполняется всегда — не смотря на появление исключительной ситуации.
Давайте посмотрим простую программу обработки исключений в Java.
А в консоле эта программа напишет такое:
Обратите внимание, что метод testException() бросает исключение, используя ключевое слово throw , а в сигнатуре метода используется ключевое слово throws , чтобы дать понять вызывающему методу тип исключений, которые может бросить testException() .
Важные моменты в обработке исключений:
- Нельзя использовать блоки catch или finally без блока try .
- Блок try также может быть использован только с catch блоком, или только с finally блоком, или с тем и другим блоком.
- Мы можем использовать несколько блоков catch только с одним try .
- try-catch блоки могут быть вложенными — этим они очень похожи на if-else конструкции.
- Мы можем использовать только один, блок finally в одном try-catch .
Иерархия исключений в Java
Java исключения являются иерархическими, а наследование используется для категоризации различных типов исключений. Throwable — родительский класс в иерархии Java исключений. Он имеет два дочерних объекта — Error и Exception . Исключения далее разделены на проверяемые исключения и исключения времени выполнения.
- Error — это тип ошибок, которые выходят за рамки вашей программы, их невозможно предвидеть или обработать. Это может быть аппаратный сбой, «поломка» JVM или ошибка памяти. Именно для таких необычных ситуаций есть отдельная иерархия ошибок. Мы должны просто знать, что такие ошибки есть и не можем справиться с такими ситуациями. Примеры Error : OutOfMemoryError и StackOverflowError .
- Проверяемые исключения (Checked Exceptions) — тип исключений, которые мы можем предвидеть в программе и попытаться обработать, например, FileNotFoundException . Мы должны поймать это исключение и написать внятное и полезное сообщение пользователю о том, что произошло (также желательно логировать ошибки). Exception — родительский класс всех проверяемых исключений (Checked Exceptions). Если мы бросили проверяемое исключение, то должны поймать его в том же методе или должны пробросить его с помощью ключевого слова throws .
- Runtime Exception — это ошибки программиста. Например, пытаясь получить элемент из массива, мы должны проверить длину массива, прежде чем пытаться получить элемент — в противном случае это может быть брошен ArrayIndexOutOfBoundException . RuntimeException — родительский класс для всех Runtime исключений. Если мы сами бросаем Runtime Exception в методе, то не обязательно указывать в сигнатуре метода ключевое слово throws .
На рисунке 1 представлена иерархия исключений в Java:
Рисунок 1 — Иерархия исключений в Java
Полезные методы в обработке исключений
Класс Exception и все его подклассы не содержат какие-либо методы для обработки исключений. Все предоставляемые методы находятся в базовом классе Throwable . Подклассы класса Exception созданы для того, чтобы определять различные виды исключений. Именно поэтому при обработке исключений мы можем легко определить причину и обработать исключение в соответствии с его типом.
Полезные методы класса Throwable :
- public String getMessage() — этот метод возвращает сообщение, которое было создано при создании исключения через конструктор.
- public String getLocalizedMessage() — метод, который переопределяют подклассы для локализации конкретное сообщение об исключении. В реализации Throwable класса этот метод просто использует метод g etMessage() , чтобы вернуть сообщение об исключении ( Throwable на вершине иерархии — ему нечего локализировать, поэтому он вызывает getMessage()) .
- public synchronized Throwable getCause() — этот метод возвращает причину исключения или идентификатор в виде null , если причина неизвестна.
- public String toString() — этот метод возвращает информацию о Throwable в формате String .
- public void printStackTrace() — этот метод выводит информацию трассировки стека в стандартный поток ошибок, этот метод перегружен и мы можем передать PrintStream или PrintWriter в качестве аргумента, чтобы написать информацию трассировки стека в файл или поток.
Автоматическое управление ресурсами и улучшения блока перехвата ошибок в Java 7
Если вам нужно перехватывать много исключений в одном блоке try-catch , то блок перехвата будет выглядеть очень некрасиво и в основном будет состоять из избыточного кода. Именно поэтому в Java 7 это было значительно улучшено и теперь мы можем перехватывать несколько исключений в одном блоке catch .
Источник
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.
Java is a universal language that helps developers create robust applications. However, runtime errors occur occasionally, which can halt the execution of your program and cause frustration.
This blog post will look at some ways to fix Java runtime error. We will also discuss how to troubleshoot common issues and find the root cause of the problem. So, if you are experiencing runtime errors in Java, read on for some helpful tips.
Contents
- 1 1. Close The Conflicting Programs:
- 2 2. Uninstall And Reinstall The Program:
- 3 3. Reduce The Input Error:
- 4 4. Install Virus Protection Program:
- 5 5. Use Load Testing Tool:
- 6 6. Run Disk Cleanup:
- 7 7. Reduce External Resource Configuration:
- 8 8. Reinstall Runtime Libraries:
- 9 9. Developer Must Build Proper Logic
- 10 10. Use Trusted Libraries
- 11 Conclusion
- 11.1 Related Posts
1. Close The Conflicting Programs:
Although runtime errors are inconvenient and persistent, they are not entirely hopeless; fixes are available. The first method you can use is to close these conflicting Programs.
- Go to the Task Manager and press Ctrl-Alt-Del. This process will display a list of currently running programs.
- Go to the Processes tab and, one by one, stop the programs by highlighting them and clicking the End Process button.
- You’ll need to check if the error notice appears again after you halt a process.
You can proceed further once you’ve identified which program generates the error and reinstalls the application.
2. Uninstall And Reinstall The Program:
If the problem persists, uninstall and reinstall the software by obtaining the most recent version. When runtime issues are discovered after a program has been released to the public, developers frequently offer fixes or tiny updates.
You can follow these steps to uninstall the program for a different Windows version.
- In Window 7, Click the Start button, Control Panel, and Uninstall a program.
- For Windows 8, go to the Start button, scroll down to More Settings, and then Control panel > Uninstall a program.
- Put Control Panel into the search box in Windows 10, click the result, and select Uninstall an application.
- Click the problem program in Programs and Features and then Update or Uninstall.
If you decided to update, follow the prompts to finish the process; if you selected to remove, follow the prompts to uninstall and then re-download or use the application’s installation DVD to reinstall the program.
3. Reduce The Input Error:
User input can corrupt an application in different ways. If the user entered less than < or excellent than > sign on the HTML comment board, it destroys that web page to load. The data cleaning converts the extended data that could be entered into the application into a safe range of values so that the program can understand and comprehend it.
The use of Java library files helps reduce run time errors due to input sanitization failure. Java Framework like Hibernate validator and Apache BVal perform explanatory input cleaning, and both frameworks also easily integrate into Java Based Applications.
4. Install Virus Protection Program:
Because malicious software can tamper with system settings and computer memory, they can occasionally cause runtime issues. Install a good antivirus tool and run it periodically to remove unwanted software from your computer to fix runtime errors caused by computer viruses. Also, make sure the Anti-virus program is the most recent updated version, run a thorough scan on your computer, or run Windows Update to receive the most recent virus definitions and fixes.
5. Use Load Testing Tool:
Some of the runtime errors of java occur due to limited resources caused by the problems of infrastructures. For Instance, Overutilization of CPU, low RAM, network timeout, or unable to schedule thread or process by the kernel.
The use of load testing tools like JMeter and LoadRunner is a simple method to avoid this type of error. These tools detect performance problems and stop applications before moving to production deployment.
Some applications may have unpredictable workloads to use a cloud-based balancing technique. This method will resolve both limited resources and purchasing expensive hardware relay.
6. Run Disk Cleanup:
A minimal amount of free space on your PC could be causing the runtime issue. It would help if you thought about backing up your stuff and clearing up hard drive distance. You can also restart your computer after clearing your cache. You can also use Disk Cleanup, go to your explorer window, and right-click your primary directory, usually C disk. Select Properties and then click Disk Cleanup.
7. Reduce External Resource Configuration:
An external resource can cause an error runtime error if one of the following situations occur:
When there are Changes in IP address, Changes in Firewall Configuration, and the maintenance of the external system.
The application must react while the resource is being changed. For Instance, the developer of APP12 keeps all configuration data external so that the application quickly responds while changing resources. It must deal with external resource change without changing the base code and avoid application rebuilding.
Another tool to avoid this problem is the chaos engineering tool randomly terminates the app depending upon that app. In such an app, developers create code that remains flexible even when external systems fail. Developers cannot control the built-in issue with external recourse, but they minimize it by controlling how applications behave while external resources fail.
8. Reinstall Runtime Libraries:
The Java runtime error message could be caused by an update, such as the MS Visual C++ package, when it did not adequately or entirely. Then you can remove the current package and replace it with a new one.
Go to Programs and Features, find and highlight the Microsoft Visual C++ Redistributable Package, and uninstall it. Uninstall the package at the top of the list and Reboot your computer when you are finished. After that, download and install the most recent Microsoft redistributable package.
9. Developer Must Build Proper Logic
Not every time runtime error is caused by data entry, but it can also be due to logical error. Sometimes code contains a logical fallacy that causes an application fails at the runtime.
Java contains the Runtime Exception feature to handle code-related runtime errors. Java17 has 78 errors in its software development kit.
Runtime Exception has the following common feature:
- Arithmetic Exception like dividing by zero error.
- Class Cast Exception like data type conversion error.
- Null Pointer Exception like when the null object calls the method.
- Index out Of Bound Exception is when the array accesses the nonexistence element.
Here you cannot do anything on your own; the developer himself must fix this.
10. Use Trusted Libraries
The complex and non-trivial applications contain many dependencies of third-party libraries to perform different tasks like input validation, logging and form handling, etc. Any error of a third-party library becomes the error of the application.
One method to reduce third-party library runtime error of dependences only use trusted libraries such as Eclipse or Apache.
Another defensive method is to update the latest version of the application regularly.
Also Check: How To Fix Android Delayed Notifications? 14 Easy Solutions
Conclusion
Java is a universal language that has many uses. While it can be challenging to learn, the benefits are worth it.
Runtime errors can be frustrating and challenging to fix. We hope that this guide has helped you understand the causes of runtime errors and how to fix them. If you still have questions or need help, please don’t hesitate to reach out to us for assistance.