Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

Declaring custom exception in Java

when I try to catch this exception it gives me a compilation error message that says, "exception LinkedListException is never thrown in body of corresponding try statement". What does this mean?

try {
        LList.Node someNode = list.nextNode(node);
        // We should not get here. 
        assertTrue(false);
    }
    catch ( LinkedListException ex) {
        // If we get here we are happy as it throw the exception
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The exception must be thrown somewhere in your code using throw keyword.

For example,

The ArithmeticException is thrown some where deep inside the code . If you don't want to handle( just like how the person thought about writing ArithmeticException) you can bubble up like

void someMethod () throws Exception
{
    throw new Exception();
}

The person who called this method have to handle it with try,catch , finally like we usually do for exceptions IOException etc.

So, if you want to throw your exception, add this throw new LinkedListException() some where in your try block where ever you want to raise an exception.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...