Runtime error java как исправить

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:

public class ArithmeticExceptionExample {
public static void main(String[] args) {
          int a = 10, b = 0;
          System.out.println("Result: "+ a/b);
    }
}

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:

Exception in thread "main" java.lang.ArithmeticException: / by zero
        at ArithmeticExceptionExample.main(ArithmeticExceptionExample.java:4)

Accessing an out of range value in an array

Here is an example of a java.lang.ArrayIndexOutOfBoundsExceptionthrown due to an attempt to access an element in an array that is out of bounds:

public class ValueOutOfRangeErrorExample {
    public static void main(String[] args) {
        int arr[] = new int[5];
        System.out.println("5th element in array: " + arr[5]);
    }
}

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:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
    at ValueOutOfRangeErrorExample.main(ValueOutOfRangeErrorExample.java:4)

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:

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

![Rollbar in action](https://rollbar.com/wp-content/uploads/2022/04/section-1-real-time-errors@2x-1-300×202.png)

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 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.

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.

Conflicting Programs

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.

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.

Virus Protection Program

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.

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.

Reinstall Runtime Libraries

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:

  1. Arithmetic Exception like dividing by zero error.
  2. Class Cast Exception like data type conversion error.
  3. Null Pointer Exception like when the null object calls the method.
  4. 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.

Build Proper Logic

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.

Maryam has been teaching IT as a school teacher for over a decade, and her main subject of choice is Internet safety, especially helping parents keep their families safe and secure online. When Maryam is not teaching or writing she is a big fan of the outdoors, the complete opposite of staring at a computer screen for hours.

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.

  1. Division by zero errors
  2.  IO errors
  3. Out of range errors
  4. 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.

  1. Accessing an element that is out of range in an array
  2. Dividing a number with 0
  3. Less space or insufficient space memory
  4. Conversion of an invalid string into a number
  5. 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:

  1. You will need to Surround the statements that are capable of throwing an exception or a runtime error in the try catch blocks.
  2. The next step is to catch the error.
  3. 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

Lets 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

Привет. Пишу олимпиаду. Проверочная компиляция проходит на сервере. Хоть у меня у самого успешно компиляция проходит, на сервере происходит Runtime error. Не могли бы вы подсказать, из-за чего может возникать такая ошибка?

Задача сама по себе элементарная (Умножение матриц)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;


class solver {

    public static void main(String[] args) throws IOException {
        int Arows, Acols;
        int Brows, Bcols;

        try {
            BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in)); // Get A array size
            String str1 = br1.readLine();
            String[] sub1 = str1.split(" ");
            Arows = Integer.parseInt(sub1[0]);
            Acols = Integer.parseInt(sub1[1]); 

        } catch (IOException e) {

            System.out.println(e.getMessage());
            return;
        } 

        int[][] Aarray = new int[Arows][Acols]; // Initialize and fill A array

        try {
            for (int i = 0; i < Arows; i++) {
                BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
                String str2 = br2.readLine();
                String[] sub2 = str2.split(" ");
                for (int j = 0; j < Acols; j++) {
                    Aarray[i][j] = Integer.parseInt(sub2[j]);
                }

            }
        } catch (IOException e) {

            System.out.println(e.getMessage());
            return;
        } 

        try {
            BufferedReader br3 = new BufferedReader(new InputStreamReader(System.in)); // Get B array size
            String str3 = br3.readLine();
            String[] sub3 = str3.split(" ");
            Brows = Integer.parseInt(sub3[0]);
            Bcols = Integer.parseInt(sub3[1]); 
        } catch (IOException e) {

            System.out.println(e.getMessage());
            return;
        } 



        int[][] Barray = new int[Brows][Bcols]; // Initialize and fill A array

        try {
            for (int i = 0; i < Brows; i++) {
                BufferedReader br4 = new BufferedReader(new InputStreamReader(System.in));
                String str4 = br4.readLine();
                String[] sub4 = str4.split(" ");
                for (int j = 0; j < Bcols; j++) {
                    Barray[i][j] = Integer.parseInt(sub4[j]);
                }

            }
        } catch (IOException e) {

            System.out.println(e.getMessage());
            return;
        } 

        if (Acols == Brows) {
            int iter;
            double res;
            double[][] Rarray = new double[Arows][Bcols]; // Initialize result array

            for (int i = 0; i < Arows; i++) {
                for (int j = 0; j < Bcols; j++) {
                    iter = 0;
                    res = 0;
                    while (iter < Acols) {
                        res = res + Aarray[i][iter]*Barray[iter][j];
                        iter = iter + 1;
                    }
                    Rarray[i][j] = res;
                }
            }
            System.out.printf(Locale.US, "%d %dn", Arows, Bcols);
            for (int i = 0; i < Arows; i++) {
                for (int j = 0; j < Bcols; j++) {
                    System.out.printf(Locale.US, "%.0f ", Rarray[i][j]);
                }
                System.out.printf(Locale.US, "n");
            }
        }
    }

}

As the name implies, runtime errors occur during the execution of a software program. They occur when an application runs. Any time an application behaves in a way that negatively deviates from its established requirements, this means a runtime error has occurred.

Such a broad definition isn’t very helpful when Java runtime errors stop your app in its tracks. Let’s take a closer look at the five most common runtime errors in Java programmers will encounter, and the steps and strategies to pursue to address them.

Top 5 runtime errors in Java

The most common runtime errors in Java can be broken into the following five categories:

  1. Data entry errors
  2. Insufficient runtime resources
  3. Poorly implemented logic
  4. External resource changes
  5. Third-party vulnerabilities

Input sanitization failures

There are innumerable ways user input can corrupt an application.

On an HTML-based comment board, a user who is allowed to innocently submit an unencoded less than (<) or greater than sign (>) has the potential to completely ruin the ability of that webpage to render. Similarly, text-processing systems built to expect all input in ASCII format can prematurely terminate if they receive emojis or nonstandard character inputs.

Key benefits of data cleansing

Data cleansing provides these benefits to organizations.

More nefariously, a favorite attack vector of hackers is SQL injection, which hides a harmful executable database query inside an otherwise innocuous input field. This not only can cause an application to fail, but potentially surrender control of the entire data layer.

The process of input sanitization, or data scrubbing, converts the broad spectrum of data that could potentially be entered into applications into a safe range of values that a program comprehends. Use of such libraries helps mitigate runtime errors caused by input sanitization failures.

Popular Java frameworks such as Apache BVal and Hibernate Validator perform simple, annotation-based input cleansing, and they integrate easily into any Java-based application.

Insufficient runtime resources

Software developers don’t shoulder the blame for every type of runtime error that occurs. Many runtime errors in Java involve resource limitations caused by problems with the underlying infrastructure. Examples include: network timeouts, out of memory conditions, CPU overutilization or an inability to schedule a thread on the processor.

One way to avoid resource-related runtime errors is to use a load testing tool, such as JMeter or LoadRunner, in an application’s CI/CD pipeline. If these tools detect a possible performance problem, they can stop the application before it moves further down the pipeline toward production deployment.

Some applications’ load varies drastically. For example, a financial services app may see steady load most of the time but be extremely busy at the end of trading day. A tax service might hit a peak load before the filing deadline but have relatively little load the rest of the year.

DevOps teams must monitor their performance metrics with tools to preemptively detect and mitigate resource-related runtime errors. Examples of such tools include JDK Flight Recorder and Java Mission Control.

For applications with completely unpredictable workloads, use cloud-based load balancing technology to allocate resources elastically. This eliminates both underallocated resources, and the trap of purchasing expensive, rarely used hardware.

Poorly implemented logic

Just because code compiles doesn’t mean it works properly. Code often contains logical problems that cause an application to fail at runtime.

Java contains a built-in construct to handle a class of common code-related runtime errors, called the RuntimeException, or the unchecked exception. Java 17 defines 78 such errors in the SDK alone, and other projects and frameworks additionally define their own RuntimeException errors.

The most commonly encountered RuntimeExceptions in Java include:

  • ArithmeticException, for divide by zero errors;
  • ClassCastException, for data type conversion errors;
  • ConcurrentModificationException, for incorrectly implemented parallel computations;
  • IndexOutOfBoundsException, when a nonexistent element in an array is accessed; and
  • NullPointerException, when a method is invoked on a null object.

Developers are not required to handle unchecked exceptions in their code. But an unchecked exception that is thrown and ignored will terminate an application.

At the very least, every application should include a generic exception harness that can catch every possible RuntimeException, log the error and allow the problematic thread of execution to die rather than abort the entire application.

External resource configuration

Enterprise applications rarely exist in an isolated bubble. They typically interact with everything from NoSQL databases and relational systems to Kafka queues and RESTful APIs. Unfortunately, if your application is unable to connect to a required, external system, this inevitably results in a runtime error.

An external resource can precipitate a runtime error if any of the following situations occur with no corresponding update to the calling program:

  • an IP address changes;
  • credentials change;
  • firewall configuration change; or
  • the external system goes down for maintenance.

Applications should react nimbly when resources change. The 12-Factor App insists developers keep all configuration data external to the application so that applications can react nimbly when resources change. The ability to update property files without changing the codebase allows applications to deal with external resource changes, and avoids an application rebuild.

Relatedly, chaos engineering tools randomly terminate the processes upon which an application depends. Such tools force developers to write code that remains responsive and resilient even when external systems fail.

The inherent problem with external resources is that developers cannot control them — but they can control how an application responds when those external resources fail. Anticipate runtime errors generated by the systems you don’t control, and write applications that respond gracefully when those external systems fail.

Third-party library vulnerabilities

Any nontrivial enterprise application includes dozens of dependencies on third-party libraries to perform functions such as logging, monitoring, input validation, form handling and more.

Unfortunately, any bugs in a third-party library become a bug in the application you deploy. This became uncomfortably real for the Java world in December 2021, as an LDAP inject flaw in the widely used Log4j 2 library forced JVMs throughout the world to go offline.

Various computer bug types spanning scope, effect and severity

Bug types can be categorized in several ways based on their contexts and effect on the user.

One way to mitigate against the possibility that software dependencies introduce runtime errors into applications is to only use trusted libraries from organizations such as Apache or Eclipse.

Another protective measure is to regularly update an application’s dependencies to the latest version as soon as updates become available.

Finally, be aware of secondary or tertiary dependencies — ones that your primary dependencies themselves rely upon — and be aware of any risks those bring with them.

In the world of software development, “perfect” is the enemy of “done.” No program is immune from the threat of an unanticipated runtime error. However, when enterprise developers raise their awareness of the possible causes and take steps to mitigate against potential threats, they can create software that minimizes the probability of encountering a runtime error.

Добавить комментарий