Runtime Error


Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible

The Java programming language was developed by sun microsystems in the early 1990s. Although it is primarily used for Internet-based applications java is a simple, efficient, general-purpose language. Java was originally designed for embedded network applications running on multiple platforms. It is a portable, object-oriented, interpreted language.

Java is extremely portable. The same Java application will run identically on any computer, regardless of hardware features or operating system, as long as it has a Java interpreter. Besides portability, another of Java’s key advantages is its set of security features which protect a PC running a Java program not only from problems caused by erroneous code but also from malicious programmes (such as viruses). You can safely run a Java applet downloaded from the Internet, because Java’s security features prevent these types of applets from accessing a PC’s hard drive or network connections. An applet is typically a small Java program that is embedded within an HTML page.

Java can be considered both a compiled and an interpreted language because its source code is first compiled into a binary byte-code. This byte-code runs on the java virtual machine (JVM), which is usually a software-based interpreter. The use of compiled byte-code allows the interpreter (the virtual machine) to be small and efficient (and nearly as fast as the CPU running native, compiled code). In addition, this byte-code gives Java its portability: it will run on any JVM that is correctly implemented, regardless of computer hardware or software configuration. Most Web browsers (such as Microsoft Internet Explorer or Netscape Communicator) contain a JVM to run Java applets.

Compared to C++ (another object-oriented language), Java code runs a little slower (because of the JVM) but it is more portable and has much better security features. The virtual machine provides isolation between an untrusted Java program and the PC running the software. Java’s syntax is similar to C++ but the languages are quite different. For example, Java does not permit programmers to implement operator overloading while C++ does. In addition, Java is a dynamic language where you can safely modify a program while it is running, whereas C++ does not allow it. This is especially important for network applications that cannot afford any downtime Also, all basic Java data types are predefined and not platform-dependent, whereas some data types can change with the platform used in C or C++ (such as the int type).

Java programs are more highly structured than C++ equivalents. All functions (or Java methods) and executable statements in Java must reside within a class while C++ allows function definitions and lines of code to exist outside of classes (as in C-style programs). Global data and methods cannot reside outside of a class in Java, whereas C++ allows this. These restrictions, though cumbersome at times, help maintain the integrity and security of Java programs and forces them to be totally object-oriented.

Another key feature of Java is that it is an open standard with publicly available source code. Sun Microsystems controls the java language and its related products but Sun’s liberal license policy contributed to the Internet community embracing Java as a standard. You can freely download all the tools you need to develop and run Java applets and applications from Sun’s Java Web site (http://java.sun.com).

Here is a simple Java program that averages numbers entered from the keyboard:

3 s2.0 B9780120683772500139 u13 45 9780120683772

In this example, the class AverageProgram (which is the program) contains only one method (function), main(). Notice that much of the syntax is the same as C or C++, including comment delimiters: you can use either C (/* */) or C++ (//) style delimiters in Java. Even the while() statement works as it would in C/C++. Output to the screen is accomplished using System.out.println(), where println() is an invoked method of the standard Java System.out object. Java also has a System.in object, for reading from the keyboard, but it must be processed to be useful. In this example, ConsoleIn is assumed to be a previously defined class (that uses System.in), which contains the method Readlnt() for reading an integer value.

As with the other programming languages we have surveyed, this was just a brief view of Java. For more details, refer to one of the Java texts in the bibliography or visit Sun Microsystems’ Java Web site (http://java.sun.com). Next we will discuss writing programs that run under a Microsoft Windows operating system.



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. … It is the JVM (Java Virtual Machine) which detects it while the program is running.

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) which 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 program to demonstrate Runtime Error  class DivByZero {    public static void main(String args[])    {        int var1 = 15;        int var2 = 5;        int var3 = 0;        int ans1 = var1 / var2;          // This statement causes a runtime error,        // as 15 is getting divided by 0 here        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 arrayclass RTErrorDemo {    public static void main(String args[])    {        int arr[] = new int[5];          // Array size is 5        // whereas this statement assigns          // value 250 at the 10th position.        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 onto 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 namesclass MisspelledVar {    public static void main(String args[])    {        int a = 40, b = 60;          // Declared variable Sum with Capital S        int Sum = a + b;          // Trying to call variable Sum        // with a small s ie. sum        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 semicolonsclass PrintingSentence {    public static void main(String args[])    {        String s = "GeeksforGeeks";          // Missing ';' at the end        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 bracesclass MissingParenthesis {    public static void main(String args[])    {        System.out.println("Printing 1 to 5 \n");        int i;          // missing parenthesis, should have        // been for(i=1; i<=5; i++)        for (i = 1; i <= 5; i++ {              System.out.println(i + "\n");        } // for loop ends      } // main ends} // class endsCompilation Error in java code:

    prog.java:10: error: ‘)’ expected for (i = 1; i <= 5; i++ { ^ 1 error Example: Incorrect format of selection statements or loopsclass IncorrectLoop {    public static void main(String args[])    {          System.out.println("Multiplication Table of 7");        int a = 7, ans;        int i;          // Should have been        // for(i=1; i<=10; 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
  3. 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 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 ‘%’)public class LErrorDemo {    public static void main(String[] args)    {        int num = 789;        int reversednum = 0;        int remainder;          while (num != 0) {              // to obtain modulus % sign should            // have been used instead of /            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 messageclass 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");          // The correct message should have        // been System.out.println        //(b+" is the largest Number");        // to make logic        else            System.out.println(                c + " is the largest Number");    }}Output:Finding the largest number 8 is the smallest Number

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.

What are the causes of runtime error?

An error that occurs during the execution of a program. In contrast, compile-time errors occur while a program is being compiled. Runtime errors indicate bugs in the program or problems that the designers had anticipated but could do nothing about. For example, running out of memorywill often cause a runtime error.


This type of error causes a program to continually use up more RAM while the program is running. … A memory leak may be due to an infinite loop, not deallocating unused memory, or other reasons.

How to Solve Runtime Errors In Java

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:

public class ArithmeticExceptionExample {
    public static void main(String[] args) {
        try {
            int a = 10, b = 0;
            System.out.println("Result: " + a/b);
        } catch (ArithmeticException ae) {
            System.out.println("Arithmetic Exception: cannot divide by 0");
        System.out.println("Continuing execution...");

Surrounding the code in try-catch blocks like the above allows the program to continue execution after the exception is encountered:

Arithmetic Exception: cannot divide by 0
Continuing execution…

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.

Drop your comment

Hits: 4

Related Post

Leave a Reply

Your email address will not be published.