How to Throw Exception in Java

How to Throw Exception in Java thumbnail
Create error handling in Java.

Error handling provides a way for Java developers to program responses to software errors. When a user enters a wrong value or the program fails due to a logic error, an exception is made through the code. If you don't handle exceptions, the software crashes on your users' machines. Therefore, Java developers "throw" exceptions, which means an error handler is created to resolve unseen issues. The "throw" command is used to create an exception in Java.

Instructions

    • 1

      Create a function to handle the exception. In this example, a function simply tells the user that an error occurred. The following code shows you how to create a function in Java:

      public void ErrorFunction()
      {
      System.out.println("An error has occurred.");
      }

    • 2

      Create the "if" statement that catches the error. You can throw an exception for any logical error in your code. In this example, an exception is thrown if the total cost of an order is $0.00. The following example shows you how to set up the statements:

      if (order_total == 0)
      {
      }

    • 3

      Throw your Java exception. The "throw" command throws the exception and calls the function you create to handle the error. The following code throws your exception handler:

      if (order_total == 0)
      {
      throw new ErrorFunction();
      }

Related Searches:

References

  • Photo Credit java hot and black image by Pix by Marti from Fotolia.com

Comments

You May Also Like

Related Ads

Featured