搜索
首页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 03, 2025 am 12:23 AM

Java在企业级应用中被广泛使用是因为其平台独立性。1)平台独立性通过Java虚拟机(JVM)实现,使代码可在任何支持Java的平台上运行。2)它简化了跨平台部署和开发流程,提供了更大的灵活性和扩展性。3)然而,需注意性能差异和第三方库兼容性,并采用最佳实践如使用纯Java代码和跨平台测试。

考虑到平台独立性,Java在物联网(物联网)设备的开发中扮演什么角色?考虑到平台独立性,Java在物联网(物联网)设备的开发中扮演什么角色?May 03, 2025 am 12:22 AM

JavaplaysigantroleiniotduetoitsplatFormentence.1)itallowscodeTobewrittenOnCeandrunonVariousDevices.2)Java'secosystemprovidesuseusefidesusefidesulylibrariesforiot.3)

描述一个方案,您在Java中遇到了一个特定于平台的问题以及如何解决。描述一个方案,您在Java中遇到了一个特定于平台的问题以及如何解决。May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java平台独立对开发人员有什么好处?Java平台独立对开发人员有什么好处?May 03, 2025 am 12:15 AM

Java'splatFormIndenceistificantBecapeitAllowSitallowsDevelostWriTecoDeonCeandRunitonAnyPlatFormwithAjvm.this“ writeonce,runanywhere”(era)橱柜橱柜:1)交叉plat formcomplibility cross-platformcombiblesible,enablingDeploymentMentMentMentMentAcrAptAprospOspOspOssCrossDifferentoSswithOssuse; 2)

将Java用于需要在不同服务器上运行的Web应用程序的优点是什么?将Java用于需要在不同服务器上运行的Web应用程序的优点是什么?May 03, 2025 am 12:13 AM

Java适合开发跨服务器web应用。1)Java的“一次编写,到处运行”哲学使其代码可在任何支持JVM的平台上运行。2)Java拥有丰富的生态系统,包括Spring和Hibernate等工具,简化开发过程。3)Java在性能和安全性方面表现出色,提供高效的内存管理和强大的安全保障。

JVM如何促进Java的'写作一次,在任何地方运行”(WORA)功能?JVM如何促进Java的'写作一次,在任何地方运行”(WORA)功能?May 02, 2025 am 12:25 AM

JVM通过字节码解释、平台无关的API和动态类加载实现Java的WORA特性:1.字节码被解释为机器码,确保跨平台运行;2.标准API抽象操作系统差异;3.类在运行时动态加载,保证一致性。

Java的较新版本如何解决平台特定问题?Java的较新版本如何解决平台特定问题?May 02, 2025 am 12:18 AM

Java的最新版本通过JVM优化、标准库改进和第三方库支持有效解决平台特定问题。1)JVM优化,如Java11的ZGC提升了垃圾回收性能。2)标准库改进,如Java9的模块系统减少平台相关问题。3)第三方库提供平台优化版本,如OpenCV。

说明JVM执行的字节码验证的过程。说明JVM执行的字节码验证的过程。May 02, 2025 am 12:18 AM

JVM的字节码验证过程包括四个关键步骤:1)检查类文件格式是否符合规范,2)验证字节码指令的有效性和正确性,3)进行数据流分析确保类型安全,4)平衡验证的彻底性与性能。通过这些步骤,JVM确保只有安全、正确的字节码被执行,从而保护程序的完整性和安全性。

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

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用