Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to create a new RunTimeException for EmptyStacks

So my task may sound simple, but it has me boggled. I have looked through code on the internet, but I cannot get to grips with. Neither can I get to grips with the slides my teacher posted. This is what is required from me.

Create a new runtime exception type called EmptyStackException.

However I have no clue how to make the method, class, variable or whatever needs to be made in order to fulfill the requirement. I have a few classes that are implementations of a DynamicArrayStack and a LinkedStack. An interface for Stack.

Any pointers would be mightily helpful.

Thanks

Mjall2

like image 488
Mjall2 Avatar asked Mar 21 '12 23:03

Mjall2


2 Answers

Create a new runtime exception type called EmptyStackException.

create type is done by

public class EmptyStackException extends RuntimeException { ... }

Now if only we knew what to put in this new type (a.k.a. class). Typically we look at the methods in the superclass and override those needing different handling. Below I have overridden some of them but delegated back to the existing class. No need to do this if you don't need to make any changes in behavior.

public class EmptyStackException extends RuntimeException {
      public EmptyStackException() {
          super();
      }
      public EmptyStackException(String s) {
          super(s);
      }
      public EmptyStackException(String s, Throwable throwable) {
          super(s, throwable);
      }
      public EmptyStackException(Throwable throwable) {
          super(throwable);
      }
    }
like image 74
Jim Avatar answered Sep 21 '22 21:09

Jim


In order to do so, you have to extend the class RuntimeException.

There are two types of Exceptions in Java: unchecked and checked exceptions. RuntimeExceptions are of the second type. This means they do not need to be explicitly handled and declared.

Normally, one uses checked exceptions when writing custom exceptions. This is done by extending the class Exception. I do not see any use-case for creating a custom RuntimeException.

Anyway, the following code shows how to write your own RuntimeException:

public class EmptyStackException extends RuntimeException{

   public EmptyStackException(String message){
      super(message);
   }

}

From within your source code you could use this by the following statement:

throw new EmptyStackException("Stack was Empty, can't pop");

For more information regarding exceptions i recommend you the following Tutorial

like image 35
Matthew Avatar answered Sep 18 '22 21:09

Matthew