Unhandled Exception in Java

前端 未结 2 441
小蘑菇
小蘑菇 2020-11-29 11:50

I\'m currently in the process of learning how to properly do custom exception and I stumbled upon a problem. Whenever I try to utilize an object of a class that throws this

2条回答
  •  旧巷少年郎
    2020-11-29 12:19

    You are using the execute method, without creating a try-catch block for the RandomWiredException which it declares that it is throwing. Java required all checked exceptions (that extend Exception) to be properly handled by the caller - either with a try-catch block, or by adding throws to the calling method (in this case, it is main, though, so it shouldn't have a throws clause).

    So the proper way to do it is like:

    public class Main {
        public static void main(String[] args) {
            double x=Math.random();
            operation op=new operation();
            try {
                op.execute(x);
            } catch ( RandomWiredException e ) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }
    

    The actual code in the catch clause is up to your application's requirements, of course.

    Note: use uppercase initial letter when you name classes. This is one of the Java styling conventions that will improve your code readability.

提交回复
热议问题