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."); } } }
출력:
예시 #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."); } } }
출력:
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:
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Java는 JVM (Java Virtual Machines) 및 바이트 코드에 의존하는 "Write Once, Everywhere 어디에서나 Run Everywhere"디자인 철학으로 인해 플랫폼 독립적입니다. 1) Java Code는 JVM에 의해 해석되거나 로컬로 계산 된 바이트 코드로 컴파일됩니다. 2) 라이브러리 의존성, 성능 차이 및 환경 구성에주의하십시오. 3) 표준 라이브러리를 사용하여 크로스 플랫폼 테스트 및 버전 관리가 플랫폼 독립성을 보장하기위한 모범 사례입니다.

java'splatformincceldenceisisnotsimple; itinvolvescomplex

Java'SplatformIndenceBenefitsWebApplicationScodetorUnonySystemwithajvm, simplifyingDeploymentandScaling.Itenables : 1) EasyDeploymentAcrossDifferentservers, 2) SeamlessScalingAcrossCloudPlatforms, 3))

thejvmistheruntimeenvironmenmentforexecutingjavabytecode, Crucialforjava의 "WriteOnce, runanywhere"capability.itmanagesmemory, executesThreads, andensuressecurity, makingestement ofjavadeveloperStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandSmetsmentsMemory

javaremainsatopchoicefordevelopersdueToitsplatformindence, 객체 지향 데 디자인, 강력한, 자동 메모리 관리 및 compehensiveStandardlibrary

Java'splatforminceldenceMeansdeveloperscanwriteCodeOnceAndrunitonAnyDevicewithoutRecompiling.thisiSocievedTheRoughthejavirtualMachine (JVM), thisTecodeIntomachine-specificinstructions, hallyslatslatsplatforms.howev

JVM을 설정하려면 다음 단계를 따라야합니다. 1) JDK 다운로드 및 설치, 2) 환경 변수 설정, 3) 설치 확인, 4) IDE 설정, 5) 러너 프로그램 테스트. JVM을 설정하는 것은 단순히 작동하는 것이 아니라 메모리 할당, 쓰레기 수집, 성능 튜닝 및 오류 처리를 최적화하여 최적의 작동을 보장하는 것도 포함됩니다.

ToensureJavaplatform Independence, followthesesteps : 1) CompileIndrunyourApplicationOnMultiplePlatformsUsingDifferentOnsandjvMversions.2) Utilizeci/CDPIPELINES LICKINSORTIBACTIONSFORAUTOMATES-PLATFORMTESTING


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!