>  기사  >  Java  >  자바 NullPointerException

자바 NullPointerException

王林
王林원래의
2024-08-30 16:13:03831검색

NullPointer 예외는 프로그래머에게 매우 자주 발생하는 Java의 예외입니다. 객체 인스턴스화가 적절하지 않을 때 발생하는 런타임 예외입니다. 개체에 null 값이 있는 것으로 선언되었습니다. 널 포인터 예외는 단순히 널 값이 포함된 참조를 사용하여 객체를 호출하려고 한다는 것을 나타냅니다. 명심해야 할 가장 중요한 점은 Java 언어가 포인터 개념을 지원하지 않기 때문에 널 포인터 예외가 포인터와 관련이 없다는 것입니다. 오히려 객체 참조와 연관되어 있습니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

구문:

런타임 오류로 지정하기 위한 Null 포인터 예외에 대한 특정 구문은 없습니다. 자동으로 나타나서 사용할 수 있게 됩니다.

Catch 예외를 선언한 다음 NullPointer 예외를 가리키고 디버그하도록 처리할 수 있습니다. NullPointerException을 디버깅하는 것은 매우 지루한 일입니다. 실행 시 객체 인스턴스화 및 참조 선언이 올바른지 확인하는 것이 필요합니다.

try {
Object obj1 = new Object(); // Instantiate a new object for the class as reference
Obj1=null; //Provide null value to the object created
Logging.log(String.format(“get the object value”, obj1.object1for reference));
}
catch(java.lang.NullPointerException exception)
{
Logging.log(exception);
}
catch(Throwable exception)
{
Logging.log(exception,false);
}

Java에서 NullPointerException이 어떻게 작동하나요?

Java의 NullPointerException은 개발자에게 전혀 바람직한 오류가 아닌 예외입니다. 런타임 시마다 예외가 발생하므로 예외를 찾는 것은 매우 어렵습니다. 따라서 그러한 예외를 찾는 것은 지루한 작업입니다. 프로그래머가 NullPointerException을 찾는 데 몇 시간이 걸립니다.

다른 용도로 개체가 필요한 경우 null로 정의된 개체를 어디에나 할당하려는 비정상적인 시도가 있을 때 발생합니다. NullPointerException을 포함한 모든 Java 오류는 다음과 같은 특정 이유로 인해 발생합니다.

  • java.lang.throwable 인터페이스가 선언될 때마다 가능한 모든 Java 오류가 발생하고 상속된 클래스에 의해 추가로 확장됩니다.
  • lang.Exception은 java.lang.throwable에서 상속받습니다.
  • lang.throwable 클래스는 java.lang.Exception을 확장합니다.
  • 이 상속된 클래스로 인해 Java.lang.RuntimeException도 발생합니다.
  • 결국 java.lang.NullPointerException은 java.lang.RuntimeException 클래스에서 상속됩니다.

NullPointerException이 java.lang.RuntimeException에서 상속된다는 것이 명확하게 언급되어 있듯이 이 문제는 애플리케이션 컴파일 및 실행 시 애플리케이션이 실행될 때마다 발생합니다. 또한 인스턴스화 시 필드, 메소드 또는 객체의 잘못된 참조에 직접 액세스하려고 할 때마다 java.lang.NullPointerException을 발생시키는 것이 매우 필요합니다. 로거를 추가한 다음 추가 더미 개체를 생성하고 null 할당 개체의 메서드 인스턴스를 호출하는 것도 코드를 적절하게 디버깅하고 NullPointerException의 근본 원인과 오류 및 예외를 가리키는 줄을 찾는 데 도움이 됩니다. 따라서 특정 라인에서 발생하는 Java 오류를 파악하기 위한 매우 일반적인 문제 해결 및 디버깅 방법입니다.

Java NullPointerException 생성자

NullPointerException의 메소드로 정의되고 선언된 특정 특정 생성자가 있으며, 이는 다음과 같습니다.

1. NullPointerException()

이 생성자는 자세한 메시지나 설명 없이 NullPointerException을 생성하는 데 사용됩니다. 요구 사항만큼 권장되지 않는 비어 있거나 null 예외로 간주될 수 있습니다.

2. NullPointerException(문자열 s)

이 생성자는 지정된 위치에서 발생하는 약간의 자세한 메시지를 포함하고 널 포인터 예외를 생성할 때 사용할 수 있는 인수를 포함하므로 NullPointerException()과 모순되게 동작합니다. String 인수는 자세한 메시지와 함께 널 포인터 예외를 생성하는 역할을 담당합니다.

Java NullPointerException 구현 예

아래는 Java NullPointerException의 예입니다.

예시 #1

이 프로그램은 실행 시 잘못된 메소드의 호출을 보여주기 위해 사용되며, 이로 인해 필요하지 않은 NullPointerException이 발생합니다.

코드:

public class Null_Pointer_Excptn {
public static void main(String[] args) {
String strng = null;
try
{
if (strng.equals("monkey"))
System.out.println("Let us take a value which needs to be similar");
else
System.out.println("Otherwise it will not take a similar and equal value.");
}
catch(NullPointerException e)
{
System.out.println("It is a need to catch the null pointer exception.");
}
}
}

출력:

자바 NullPointerException

예시 #2

이 프로그램은 일반적인 방법이 아니기 때문에 NullPointerException이 발생하지 않도록 하는 Java 프로그램을 보여줍니다.

코드:

public class Null_Pointer_Excptn_Avoid {
public static void main(String[] args) {
String strng2 = null;
try
{
if ("avoid_null".equals(strng2))
System.out.println("Coming out to be equal");
else
System.out.println("It is not at all coming out to be equal");
}
catch(NullPointerException e)
{
System.out.println("Catch the null pointer Exception to get a clarification.");
}
}
}

출력:

자바 NullPointerException

Example #3

This program illustrates that the NullPointerException can be avoided using the proper object verification before initialization.

Code:

public class Good_Null_Pntr_Excpn {
public static void main(String[] args) {
String store = "Learning";
try
{
System.out.println(getLength(store));
}
catch(IllegalArgumentException e)
{
System.out.println("Need to catch the definition of illegalArgument.");
}
store = "Educba";
try
{
System.out.println(getLength(store));
}
catch(IllegalArgumentException e)
{
System.out.println("Need to catch the definition of illegalArgument.");
}
store = null;
try
{
System.out.println(getLength(store));
}
catch(IllegalArgumentException e)
{
System.out.println("Need to catch the definition of illegalArgument.");
}
}
public static int getLength(String store)
{
if (store == null)
throw new IllegalArgumentException("Need to catch the definition of illegalArgument.");
return store.length();
}
}

Output:

자바 NullPointerException

How to Avoid NullPointerException?

As it is not a good practice to get NullPointerException as it makes the entire codebase cumbersome and consumes time for the programmers to figure out the root cause of the NullPointerException.

Therefore, it is very much needed to avoid these exceptions which can make sure using the following ways:

  • By comparing a string with the literals.
  • By keeping a check on the passed arguments or parameters being passed from the method.
  • By making use of the ternary operator.

Conclusion

Java NullPointerException is an exception which is not a good option and is recommended not to occur as it consumes a lot of time. Debugging and troubleshooting become difficult; therefore, it must keep in mind that before the initialization of the object, the reference of the object must be proper. Therefore, the reference of the object’s null value should be proper, and then it can be avoided.

위 내용은 자바 NullPointerException의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:자바의 BinarySearch()다음 기사:자바의 BinarySearch()