JavaRush /Java Blog /Random EN /6 Java exceptions that plague newbies
gram2005
Level 30

6 Java exceptions that plague newbies

Published in the Random EN group
From time to time I come across new developers who are stuck on understanding the following simple exceptions and I have to explain everything to them all over again. Most likely, many experienced Java developers find themselves in a similar situation and help newbies cope with the following exceptions. Therefore, I decided to write this article and refer to it in the future. Comments and additions to the exclusion list are welcome. 6 Java exceptions that plague newbies - 1
  1. NoClassDefFoundError: This is one of those exceptions that Exception in thread “main“ NoClassDefFoundErroroften welcomes new developers into the world of Java programming. They write a helloworld program, go to the command line and write “ java ” - the command to execute and “BAM” :-) After a while, beginners will understand how to fix this exception and see how their hello world is printed.

    NoClassDefFoundErrorhappens when the Java Virtual Machine (JVM) tries to access a class at runtime and the class is not found even though the same class was present at compile time. Most often, this exception occurs when running a Java program through the “java“ command with an invalid parameter value classpath. [ Classpathis a parameter that is set via the command line or through an environment variable, indicating to the Java virtual machine or Java compiler where to look for classes or packages declared by the user - approx. translator] Possible reasons for exclusion:

    • Class not available in Classpath.
    • Often the script that is executed when the operating system starts changes the value of the environment variable classpath. You can check this by running the “ set” command on the Windows command line and seeing if the class definition is included in the value classpath. If you wish, you can further explore this exception on the Javarevisited blog .
  2. ClassNotFoundException: Exception ClassNotFoundExceptionis another exception that gives newbies who are just starting out with Java programming nightmares. Interestingly, it takes some time for the average developer to stop confusing ClassNotFoundExceptioneach NoClassDefFoundErrorother. And therefore, the question about the difference between these two exceptions remains one of the most frequently asked questions during interviews for the position of junior Java developer.
    ClassNotFoundExceptionhappens when the JVM tries to load a certain class and does not find the same in the classpath. Usually beginners encounter this in code that connects to a database using the JDBC library. Trying to load a driver using the following code Class.forName( “JDBCdriver”). Good material on this ClassNotFoundExceptioncan be found here . It is also recommended that you familiarize yourself with and understand the concept of class loaders in Java to effectively deal with this exception. You might want to see the next page on how to configure classpath in Win/Unix environments . And so, as follows from the Java documentation, this exception occurs in the following cases:

    1. When trying to load a class using a method Class.forNameand the file .classdoes not exist in the classpath. This is the most common case of all three.
    2. When a class loader tries to load a class using the loadClass.
    3. When a class loader tries to load a class using findSystemClass.
  3. NullPointerException: the exception NullPointerExceptionis easier to understand and beginners cope with it faster than the previous two. At the same time, the reason for the exception is very easy to find since the line number where it occurred is given. First of all, the exception occurs when the JVM tries to access null in the place where the object should have been. Most often this happens when the JVM tries to call a method using an object and it turns out that the object is equal to null. Other cases, as mentioned in the Java documentation, could be the following:

    1. By accessing or changing a method of an object that is null.
    2. Getting the length of the array when it is equal to null.
    3. By accessing or changing objects that are enclosed in an array that is null.
    Самый простой способ избежать этого исключения это добавить проверку на неequalsство null (далее – проверка на null – прим. переводчика). Поэтому рано or поздно разработчик начинает это использовать и тогда проверки на null появляются везде. Интересно что использовать везде проверку на null не считается примером хорошего программирования. Основная причина почему проверка на null используется разработчиками это передавать an object null в случаи ошибки. В место этого пример хорошего программирования, который должен пропагандироваться программистами, это передавать пустой an object когда condition для главной/рабочей ветви программы не удовлетворяется. Это в свою очередь уменьшило бы количество проверок на null. Все-таки легче говорить нежели применять это на практике.:)

  4. ClassCastException: это еще одно из исключений, с которым знакомятся новички когда пытаются привести an object к классу, экземпляром которого он не является. Опять же его довольно легко понять, найти причину и исправить. Один из способов избежать этого исключения, когда во время исполнения тип an object не известен, это использовать проверку является ли an object экземпляром определенного класса: “instanceof”.

  5. ArrayIndexOutOfBoundsException: название этого исключения говорит само за себя. Оно случается когда JVM пытается получить доступ к элементу массива используя неверный индекс, на пример, отрицательный (-1) or больший or равный размеру массива. Его легко понять, найти причину и исправить. Следующий пример codeа поможет избежать этого исключения: for( index = 0; index < array.length; index++ )
    Обратите внимание что индекс начинается с 0 и возрастает до величины на 1 меньше размера массива.

  6. IllegalArgumentException: Это исключение самое простое, его легко понять, найти его причину и исправить. Оно случается когда JVM пытается передать методу неподходящий аргумент or аргумент неправильного типа.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION