I tried using try-catch block to catch NullPointerException
but still the following program is giving errors. Am I doing something wrong or is there any other way to catch NullPointerException
in the following program. Any help is highly appreciated.
public class Circular_or_not { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { LinkedListNode[] nodes = new LinkedListNode[10]; for (int i = 0; i < 10; i++) { nodes[i] = new LinkedListNode(i, null, i > 0 ? nodes[i - 1] : null); } // Create loop; // nodes[9].next = nodes[3]; Boolean abc= Check_Circular(nodes[0]); System.out.print(abc); } catch(NullPointerException e) { System.out.print("NullPointerException caught"); } } public static boolean Check_Circular(LinkedListNode head) { LinkedListNode n1 = head; LinkedListNode n2 = head; // Find meeting point while (n2.next != null) { n1 = n1.next; n2 = n2.next.next; if (n1 == n2) { return true; } } return false; } }
It is generally a bad practice to catch NullPointerException. Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem.
How to avoid the NullPointerException? To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.
In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
There is nothing wrong with catching NullPointerException and doing something with it. This goes for any exception. The general idea is to catch exceptions that can be dealt with, and not catch (pass up) those that can't be handled.
NullPointerException
is a run-time exception which is not recommended to catch it, but instead avoid it:
if(someVariable != null) someVariable.doSomething(); else { // do something else }
As stated already within another answer it is not recommended to catch a NullPointerException. However you definitely could catch it, like the following example shows.
public class Testclass{ public static void main(String[] args) { try { doSomething(); } catch (NullPointerException e) { System.out.print("Caught the NullPointerException"); } } public static void doSomething() { String nullString = null; nullString.endsWith("test"); } }
Although a NPE can be caught you definitely shouldn't do that but fix the initial issue, which is the Check_Circular method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With