-
NoClassDefFoundError
: This is one of those exceptions thatException in thread “main“ NoClassDefFoundError
often 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.NoClassDefFoundError
happens 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 valueclasspath
. [Classpath
is 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 valueclasspath
. If you wish, you can further explore this exception on the Javarevisited blog .
- Class not available in
-
ClassNotFoundException
: ExceptionClassNotFoundException
is 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 confusingClassNotFoundException
eachNoClassDefFoundError
other. 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.ClassNotFoundException
happens when the JVM tries to load a certain class and does not find the same in theclasspath
. Usually beginners encounter this in code that connects to a database using the JDBC library. Trying to load a driver using the following codeClass.forName( “JDBCdriver”)
. Good material on thisClassNotFoundException
can 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:- When trying to load a class using a method
Class.forName
and the file.class
does not exist in theclasspath
. This is the most common case of all three. - When a class loader tries to load a class using the
loadClass
. - When a class loader tries to load a class using
findSystemClass
.
- When trying to load a class using a method
-
NullPointerException
: the exceptionNullPointerException
is 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 tonull
. Other cases, as mentioned in the Java documentation, could be the following:- By accessing or changing a method of an object that is
null
. - Getting the length of the array when it is equal to
null
. - By accessing or changing objects that are enclosed in an array that is
null
.
null
(далее – проверка на null – прим. переводчика). Поэтому рано or поздно разработчик начинает это использовать и тогда проверки на null появляются везде. Интересно что использовать везде проверку наnull
не считается примером хорошего программирования. Основная причина почему проверка наnull
используется разработчиками это передавать an objectnull
в случаи ошибки. В место этого пример хорошего программирования, который должен пропагандироваться программистами, это передавать пустой an object когда condition для главной/рабочей ветви программы не удовлетворяется. Это в свою очередь уменьшило бы количество проверок наnull
. Все-таки легче говорить нежели применять это на практике.:) - By accessing or changing a method of an object that is
ClassCastException
: это еще одно из исключений, с которым знакомятся новички когда пытаются привести an object к классу, экземпляром которого он не является. Опять же его довольно легко понять, найти причину и исправить. Один из способов избежать этого исключения, когда во время исполнения тип an object не известен, это использовать проверку является ли an object экземпляром определенного класса: “instanceof
”.ArrayIndexOutOfBoundsException
: название этого исключения говорит само за себя. Оно случается когда JVM пытается получить доступ к элементу массива используя неверный индекс, на пример, отрицательный (-1) or больший or равный размеру массива. Его легко понять, найти причину и исправить. Следующий пример codeа поможет избежать этого исключения:for( index = 0; index < array.length; index++ )
Обратите внимание что индекс начинается с 0 и возрастает до величины на 1 меньше размера массива.-
IllegalArgumentException
: Это исключение самое простое, его легко понять, найти его причину и исправить. Оно случается когда JVM пытается передать методу неподходящий аргумент or аргумент неправильного типа.
gram2005
Level 30
6 Java exceptions that plague newbies
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.
GO TO FULL VERSION