Need to create a new RunTimeException for EmptyStacks

后端 未结 3 817
不思量自难忘°
不思量自难忘° 2021-01-05 00:38

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

3条回答
  •  孤街浪徒
    2021-01-05 01:07

    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

提交回复
热议问题