How to Disable a Java Exception

When the Java Virtual Machine is running a program, many error conditions cause the runtime to raise (or, in Java parlance, "throw") an exception. Exceptions are Java objects in their own right; for example, there is an ArithmeticException class that gets thrown when the program attempts to divide by zero. Java programs can anticipate the possibility that an exception of a given type will occur, and transfer control to application-dependent, exception-handling code if and when the exception happens. You can write a handler for a Java exception -- if there is no handler, the uncaught exception will cause your program to abort immediately.

Instructions

    • 1

      Include the following line at the beginning of your Java code:

      include java.lang.Exception;

    • 2

      Specify which exceptions your method can throw when declaring it, as in the following sample code:

      public void mySwap(int[] sequence, int from, int to) throws ArrayIndexOutOfBoundsException {

      int tmp;

      tmp=sequence[from];

      sequence[from]=sequence[to];

      sequence[to]=tmp;

      }

      ArrayIndexOutOfBoundsException is an exception class pre-defined as part of the Java libraries.

    • 3

      Write a handler for that particular exception type whenever you call your method, as in the following example:

      int[] samples={36,567,76,3536362,9}

      try {

      mySwap(samples,2,5);

      } catch (ArrayIndexOutOfBoundsException e) {

      System.out.println("mySwap() threw exception");

      }

      The code following "catch" is the exception handler. It can do whatever your application needs to do to recover from that particular exception.

Related Searches:

References

Comments

You May Also Like

  • How to Throw Exception in Java

    Error handling provides a way for Java developers to program responses to software errors. When a user enters a wrong value or...

  • Java Download Problems

    Java is a programming language that allows you to play games, view 3D images, chat with people. It is a free application...

  • How to Create Exception Classes in Java

    The Java programming language takes an exceptions-based approach to handling error detection and handling in code. Rather than create a complex system...

  • How to Avoid Null Pointer Exception in Java

    Null pointer exceptions are errors thrown by the Java compiler when the programmer attempts to use a variable that hasn't been defined....

Related Ads

Featured