Common runtime exceptions in java

Common runtime exceptions in java

  • The basics of TOGAF certification and some ways to prepare TOGAF offers architects a chance to learn the principles behind implementing an enterprise-grade software architecture, including.
  • Haskell vs. PureScript: The difference is complexity Haskell and PureScript each provide their own unique development advantages, so how should developers choose between these two .
  • A quick intro to the MACH architecture strategy While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .
  • Postman API platform will use Akita to tame rogue endpoints Akita’s discovery and observability will feed undocumented APIs into Postman’s design and testing framework to bring them into .
  • How to make use of specification-based test techniques Specification-based techniques can play a role in efficient test coverage. Choosing the right techniques can ensure thorough .
  • GitHub Copilot Chat aims to replace Googling for devs GitHub’s public beta of Copilot Chat rolls out GPT-4 integration that embeds a chat assistant into Visual Studio, but concerns .
  • Navigate multi-cloud billing challenges Keeping track of cloud bills from multiple clouds or accounts can be complex. Learn how to identify multi-cloud billing .
  • 5 Google Cloud cost optimization best practices Cost is always a top priority for enterprises. For those considering Google Cloud, or current users, discover these optimization .
  • How to create and manage Amazon EBS snapshots via AWS CLI EBS snapshots are an essential part of any data backup and recovery strategy in EC2-based deployments. Become familiar with how .
  • BrightTALK @ Black Hat USA 2022 BrightTALK’s virtual experience at Black Hat 2022 included live-streamed conversations with experts and researchers about the .
  • The latest from Black Hat USA 2023 Use this guide to Black Hat USA 2023 to keep up on breaking news and trending topics and to read expert insights on one of the .
  • API keys: Weaknesses and security best practices API keys are not a replacement for API security. They only offer a first step in authentication — and they require additional .
  • AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
  • Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
  • Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .
Читайте также:  Styled components ref typescript

Источник

Java exception API hierarchy — Error, Exception and RuntimeException

This article helps you understand about the core classes that make up the Java exception API as well as a list of standard errors and exceptions defined by JDK.

1. Java Exception API Hierarchy

ExceptionAPI

As you can see, Throwable is at the top of the hierarchy. It is the supertype of all exceptions and errors in Java. Below Throwable , there are 3 subtypes:

  • Error : represents system errors occurred in abnormal conditions. It is the base class for all errors in Java. Remember that we should not catch errors, because the program cannot be recovered in the events of errors. You may know two well-known errors are StackOverflowError and OutOfMemoryError .
  • Exception : is the base class for all exceptions in Java. And most of the time, we throw and catch exceptions which are sub classes of Exception .
  • RuntimeException : an exception of this type represents a programming error and typically we should not throw and catch runtime exceptions. NullPointerException is a very well-know runtime exception in Java.

2. Common Errors in Java

  • AssertionError
  • AWTError (java.awt)
  • IOError (java.io)
  • LinkageError
    • ExceptionInInitializerError
    • NoClassDefFoundError
    • UnsatisfiedLinkError
    • VerifyError
    • InternalError
    • OutOfMemoryError
    • StackOverflowError
    • UnknownError

    3. Common Exceptions in Java

    These exceptions are categorized as checked exceptions and they are grouped by package. The following is a list of common checked exceptions defined in the java.lang package:

    • ReflectiveOperationException
      • ClassNotFoundException
      • InstantiationException
      • IllegalAccessException
      • InvocationTargetException
      • NoSuchFieldException
      • NoSuchMethodException
    • CloneNotSupportedException
    • InterruptedException

    4. Common Runtime Exceptions in Java

    These exceptions are categorized as unchecked exceptions and they are grouped by package. The following is a list of common unchecked exceptions in the java.lang package:

    • ArithmeticException
    • IndexOutOfBoundsException
      • ArrayIndexOutOfBoundsException
      • StringIndexOutOfBoundsException
    • ArrayStoreException
    • ClassCastException
    • EnumConstantNotPresentException
    • IllegalArgumentException
      • IllegalThreadStateException
      • NumberFormatException

      Other Java Exception Handling Tutorials:

      About the Author:

      Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

      Источник

      How to Solve the Most Common Runtime Errors in Java

      How to Solve the Most Common Runtime Errors in 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.ArrayIndexOutOfBoundsException thrown 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.

      «Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind.»

      Источник

Оцените статью