Learning Java/Error handling II

From Wikiversity
Jump to navigation Jump to search

Finally - Generating exceptions ![edit | edit source]

All exceptions are classes. To get you started, I will show you some code:

class AnotherException extends Exception
{	
   AnotherException(String S)
   {
      super(S);
   }

   public void printStackTrace()
   {
      super.printStackTrace();
   }
}

Notice the utter simplicity. This is the first part of making exceptions. In the constructor, it calls its super class, Exception. In printStackTrace it also calls the super class. The method printStackTrace() will print the error message. Again, note the simplicity!

The second, harder part[edit | edit source]

What is the use of creating an exception class by itself? It isn't used anywhere... yet! We will make a class and method that throws this exception. We will name the class Use_Exceptions. The class will ask for an int through a window. It will convert the integer to a string and use the try/catch method to do the NumberFormatException. Then, it will throw this exception if the integer is negative. Again, some code:

public class Use_Exceptions
{
   public throwExc(String toInt) throws AnotherException
   {
      int myInt=0;
      try{
         myInt = Integer.parseInt(toInt)
      }

      catch(NumberFormatException nfe)
      {
         System.exit(0);//Exit the program
      }
      
      if(int myInt < 0)
      {
         throw new AnotherException("Bad Integer - Negative");
      }
   }
}

The "new" creates a new AnotherException. "throw" throws it - executes the exception. Let's make something that uses this:

Use_Exceptions prog=new Use_Exceptions();
try{
   Use_Exceptions.throwsExc("-25");
}
catch(AnotherException ae)
{
   ae.printStackTrace();
}

Just like the normal try/catch block!