搜尋
首頁Javajava教程Java 空指標異常

Java 空指標異常

Aug 30, 2024 pm 04:13 PM
java

NullPointer Exception是java中程式設計師常出現的異常。這是當物件實例化不正確時發生的運行時異常。該物件被聲明為其中包含空值。空指標異常僅表示它正在嘗試使用其中包含空值的參考來呼叫物件。最重要的是要記住,空指標異常與指標無關,因為 java 語言不支援指標概念;相反,它與物件引用相關聯。

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

文法:

沒有特定的語法將空指標異常指定為運行時錯誤;它會自動出現並變得可見以供使用。

可以宣告並拋出一個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);
}

NullPointerException 在 Java 中如何運作?

Java 中的 NullPointerException 是一個對開發人員來說根本不是一個更好的錯誤的例外。異常很難發現,因為它每次都會在運行時發生。因此,找到這樣的異常是一項繁瑣的任務。程式設計師需要花費幾個小時才能找出 NullPointerException。

當其他事情需要物件時,在任何地方不尋常地嘗試指派 null 定義的物件時,就會出現這種情況。所有java錯誤,包括NullPointerException,都是因為某些原因而發生的,例如:

  • 每當聲明 java.lang.the 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(String s)

這個建構函式的行為與 NullPointerException() 相矛盾,因為它包含了在指定位置引起的一些詳細訊息,並且它將涉及在建構空指標異常時可以使用的參數。參數 String s 負責建立帶有詳細訊息的空指標異常。

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.");
}
}
}

輸出:

Java 空指標異常

範例#2

此程序說明了 java 程序,它避免了 NullPointerException 的創建,因為它不是常規方法。

代碼:

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.");
}
}
}

輸出:

Java 空指標異常

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:

Java 空指標異常

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.

以上是Java 空指標異常的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Java平台獨立性:這對開發人員意味著什麼?Java平台獨立性:這對開發人員意味著什麼?May 08, 2025 am 12:27 AM

Java'splatFormIndependecemeansDeveloperScanWriteCeandeCeandOnanyDeviceWithouTrecompOlding.thisAcachivedThroughThroughTheroughThejavavirtualmachine(JVM),WhaterslatesbyTecodeDecodeOdeIntComenthendions,允許univerniverSaliversalComplatibilityAcrossplatss.allospplats.s.howevss.howev

如何為第一次使用設置JVM?如何為第一次使用設置JVM?May 08, 2025 am 12:21 AM

要設置JVM,需按以下步驟進行:1)下載並安裝JDK,2)設置環境變量,3)驗證安裝,4)設置IDE,5)測試運行程序。設置JVM不僅僅是讓其工作,還包括優化內存分配、垃圾收集、性能調優和錯誤處理,以確保最佳運行效果。

如何查看產品的Java平台獨立性?如何查看產品的Java平台獨立性?May 08, 2025 am 12:12 AM

toensurejavaplatFormIntence,lofterTheSeSteps:1)compileAndRunyOpplicationOnmultPlatFormSusiseDifferenToSandjvmversions.2)upureizeci/cdppipipelinelikeinkinslikejenkinsorgithikejenkinsorgithikejenkinsorgithikejenkinsorgithike forautomatecross-plateftestesteftestesting.3)

Java的現代發展功能:實用概述Java的現代發展功能:實用概述May 08, 2025 am 12:12 AM

javastandsoutsoutinmoderndevelopmentduetoitsrobustfeatureslikelambdaexpressions,streams,andenhanced concurrencysupport.1)lambdaexpressionssimplifyfunctional promprogientsmangional programmanging,makencodemoreconciseandable.2)

掌握Java:了解其核心功能掌握Java:了解其核心功能May 07, 2025 pm 06:49 PM

Java的核心特點包括平台獨立性、面向對象設計和豐富的標準庫。 1)面向對象設計通過多態等特性使得代碼更加靈活和可維護。 2)垃圾回收機制解放了開發者的內存管理負擔,但需要優化以避免性能問題。 3)標準庫提供了從集合到網絡的強大工具,但應謹慎選擇數據結構以保持代碼簡潔。

爪哇可以到處跑嗎?爪哇可以到處跑嗎?May 07, 2025 pm 06:41 PM

Yes,Javacanruneverywhereduetoits"WriteOnce,RunAnywhere"philosophy.1)Javacodeiscompiledintoplatform-independentbytecode.2)TheJavaVirtualMachine(JVM)interpretsorcompilesthisbytecodeintomachine-specificinstructionsatruntime,allowingthesameJava

JDK和JVM有什麼區別?JDK和JVM有什麼區別?May 07, 2025 pm 05:21 PM

jdkincludestoolsfordEveloping and compilingjavacode,whilejvmrunsthecompiledbytecode.1)jdkcontainsjre,編譯器,andutilities.2)

Java功能:快速指南Java功能:快速指南May 07, 2025 pm 05:17 PM

Java的關鍵特性包括:1)面向對象設計,2)平台獨立性,3)垃圾回收機制,4)豐富的庫和框架,5)並發支持,6)異常處理,7)持續演進。 Java的這些特性使其成為開發高效、可維護軟件的強大工具。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。