How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

前端 未结 2 500
甜味超标
甜味超标 2020-11-27 21:20

I am new to Java and kind of new to programming (I know diving straight into Java probably wasn\'t the greatest idea.) and I\'ve been getting an error consistently no matter

相关标签:
2条回答
  • 2020-11-27 21:53

    Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.

    You either need to catch it:

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
        // handle the exception...        
        // For example consider calling Thread.currentThread().interrupt(); here.
    }
    

    Or declare that your method can throw an InterruptedException:

    public static void main(String[]args) throws InterruptedException
    

    Related

    • Lesson - Exceptions
    • When does Java's Thread.sleep throw InterruptedException?
    • Java theory and practice: Dealing with InterruptedException
    0 讨论(0)
  • 2020-11-27 22:10

    You can get rid of the first line. You don't need import java.lang.*;

    Just change your 5th line to:

    public static void main(String [] args) throws Exception
    
    0 讨论(0)
提交回复
热议问题