NullPointerException – Handle by throw

NullPointerException is run time error, when we display object and do not find any value in object.

In this blog, we will see how this exception handles by throw keyword.

 

This example and video work on throw keyword.

class A

{

            void method1()

            {

                        try

                        {

                                    //throw new NullPointerException(“Error Message”);

                                    NullPointerException ob = new NullPointerException(“Error Message”);

                                    throw ob;

                        }          

                        catch(NullPointerException ex)

                        {

                                    System.out.println(“Sub : ” + ex);

                                    throw ex;        // Re-Throw  call to origin

                        }

            }

}

class Exc7

{

                        public static void main(String args[])

                        {

                                    try

                                    {

                                                A obj = new A();

                                                obj.method1();           // Call to method1() in class A

                                    }

                                    catch(NullPointerException ex)

                                    {

                                                System.out.println(“Main : ” + ex);

                                    }

                        }

}          

Output:

Sub: java.lang.NullPointerExceptions: Error Message

Main: java.lang.NullPointerExceptions: Error Message

 

 

Important Step: NullPointerException

1st Create an object and call to method1() in class A

2nd Create an object of NullPointerExceptions class with parameter constructor value

3rd We pass this object in catch block using of throw keyword

4th Display error message in catch block then re-throw in main method catch block.

4th Display error message in main method catch block.

 

 

 

 

 

Video available on YouTube now.

 


[sbscrbr_form]

If you have query about this blog, you can directly post comment or subscribe on website.


Earn money online

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

517total visits,1visits today


mayank

Hello, I am Maddy a Java blogger, trainer and developer

Related articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Your comments (*)

Name (*)

Your full name please.

Email address (*)

Used for gravatar.

Website

Link back if you want.

Enter Captcha Here :*

Reload Image

EmailEmail
PrintPrint