专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java空指针异常解决方案

Java空指针异常解决方案

更新时间:2022-11-15 10:50:52 来源:赢咖4 浏览873次

NullPointerException是一个 RuntimeException。在Java中,可以将特殊的空值分配给对象引用。当程序尝试使用具有空值的对象引用时抛出 NullPointerException。

这些可以是:

从空对象调用方法。

访问或修改空对象的字段。

取null的长度,就好像是一个数组一样。

访问或修改空对象的槽,就像它是一个数组一样。

抛出 null,就好像它是一个 Throwable 值一样。

当您尝试通过空对象进行同步时。

为什么我们需要空值?

Null 是 Java 中使用的特殊值。主要用于表示没有给引用变量赋值。null 的一种应用是实现链表和树等数据结构。其他应用程序包括 Null Object 模式和Singleton 模式。单例模式确保只创建一个类的一个实例,并且旨在提供对对象的全局访问点。

最多创建一个类的一个实例的示例方法是将其所有构造函数声明为私有的,然后创建一个返回该类的唯一实例的公共方法:

// To use randomUUID function.
import java.util.UUID;
import java.io.*;
class Singleton
{
	// Initializing values of single and ID to null.
	private static Singleton single = null;
	private String ID = null;
	private Singleton()
	{
		/* Make it private, in order to prevent the
		creation of new instances of the Singleton
		class. */
		// Create a random ID
		ID = UUID.randomUUID().toString();
	}
	public static Singleton getInstance()
	{
		if (single == null)
			single = new Singleton();
		return single;
	}
	public String getID()
	{
		return this.ID;
	}
}
// Driver Code
public class TestSingleton
{
	public static void main(String[] args)
	{
		Singleton s = Singleton.getInstance();
		System.out.println(s.getID());
	}
}

输出:

10099197-8c2d-4638-9371-e88c820a9af2

在上面的示例中,单例类的静态实例。该实例最多在 Singleton getInstance 方法中初始化一次。

如何避免 NullPointerException?

为避免 NullPointerException,我们必须确保在使用它们之前正确初始化所有对象。当我们声明一个引用变量时,在我们从对象请求方法或字段之前,我们必须验证对象不为空。

以下是克服该问题的解决方案的常见问题。

案例 1:字符串与文字的比较

一个非常常见的案例问题涉及字符串变量和文字之间的比较。文字可以是字符串或枚举的元素。不要从空对象调用方法,考虑从字面量调用它。

// A Java program to demonstrate that invoking a method
// on null causes NullPointerException
import java.io.*;
class GFG
{
	public static void main (String[] args)
	{
		// Initializing String variable with null value
		String ptr = null;
		// Checking if ptr.equals null or works fine.
		try
		{
			// This line of code throws NullPointerException
			// because ptr is null
			if (ptr.equals("gfg"))
				System.out.print("Same");
			else
				System.out.print("Not Same");
		}
		catch(NullPointerException e)
		{
			System.out.print("NullPointerException Caught");
		}
	}
}

输出:

捕获空指针异常

我们可以通过对文字而不是对象调用 equals 来避免 NullPointerException。

// A Java program to demonstrate that we can avoid
// NullPointerException
import java.io.*;
class GFG
{
	public static void main (String[] args)
	{
		// Initializing String variable with null value
		String ptr = null;
		// Checking if ptr is null using try catch.
		try
		{
			if ("gfg".equals(ptr))
				System.out.print("Same");
			else
				System.out.print("Not Same");		
		}
		catch(NullPointerException e)
		{
			System.out.print("Caught NullPointerException");
		}
	}
}

输出:

不一样

案例 2:检查方法的参数

在执行新方法的主体之前,我们应该首先检查其参数是否为空值,然后只有在正确检查参数后才继续执行该方法。否则,它将抛出IllegalArgumentException并通知调用方法传递的参数有问题。

// A Java program to demonstrate that we should
// check if parameters are null or not before
// using them.
import java.io.*;
class GFG
{
	public static void main (String[] args)
	{
		// String s set an empty string and calling getLength()
		String s = "";
		try
		{
			System.out.println(getLength(s));
		}
		catch(IllegalArgumentException e)
		{
			System.out.println("IllegalArgumentException caught");
		}
		// String s set to a value and calling getLength()
		s = "GeeksforGeeks";
		try
		{
			System.out.println(getLength(s));
		}
		catch(IllegalArgumentException e)
		{
			System.out.println("IllegalArgumentException caught");
		}
		// Setting s as null and calling getLength()
		s = null;
		try
		{
			System.out.println(getLength(s));
		}
		catch(IllegalArgumentException e)
		{
			System.out.println("IllegalArgumentException caught");
		}
	}
	// Function to return length of string s. It throws
	// IllegalArgumentException if s is null.
	public static int getLength(String s)
	{
		if (s == null)
			throw new IllegalArgumentException("The argument cannot be null");
		return s.length();
	}
}

输出:

0
13
捕获到 IllegalArgumentException

 

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>