简体   繁体   中英

Java Try Catch NullPointerException

I was trying an example about try catch but it isn't working as I wanted. This is the code :

public static void main(String[] args)
{
    //This array's size is 5 and it has 4 Strings in it. 
    String[] array = new String[5];
    array[0] = "Hello";
    array[1] = "World";
    array[2] = "try catch";
    array[4] = "error";

    try
    {
        for(int i = 0 ; i<array.length ; i++)
            System.out.println("This array has: "+array[i]);

    } catch (NullPointerException e)
    {
        System.out.println("Null!!!");
    }
}

output is like that :

This array has: Hello

This array has: World

This array has: try catch

This array has: null

This array has: error

It supposed to enter catch block but it didn't. Any ideas?

A NullPointerException occurs when a method is called on an object reference that is null or you attempt to access a null array. But that doesn't occur here. The array is initialized properly. Even though you didn't initialize array[3] , the NPE doesn't occur here.

What does occur here is String conversion (JLS, Section 5.1.11) .

If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

A null String is converted to the String "null" when concatenated, so no NPE occurs.

The elements of object arrays (all types except primitives) are initialized to null . When a null element is printed, the string literal "null" is displayed as shown in the below snippet of PrintStream#print used by System.out.println :

public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
}

Note that it's a bad practice to catch NullPointerException s. If it were a checked exception, the compiler would have probably flagged that the exception can never occur.

It's not supposed to get into the 'catch' block. there is no NullPointerException for REQUESTING array[i] even if it happens to hold null. You will get an exception if you try to do anything with this null, eg array[i].toLowerCase()

The elements of array are initialized as null. If you want to get NullPointerException, try to use String methods like;

array[i].toLowerCase()

Try to do something with the string to create an error.

Do something like 'split(String regex)' this will cause the script to blow up cause you trying to split a null value. It will hit the catch portion of your script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM