【问题标题】:How can I retry a try-catch after I catch an IllegalStateException?捕获 IllegalStateException 后如何重试 try-catch?
【发布时间】:2020-09-26 03:18:12
【问题描述】:

我知道之前有人问过这个问题,但我无法在我的代码中实现它。如果我捕捉到了,如何再次重试 try-catch 块?

if(mediaPlayer!=null){

            try {
                mediaPlayer.start();
                songEnded = 0;
            } catch(IllegalStateException e) {
                // media player is not initialized
                
                //TRY AGAIN

            }


        }

【问题讨论】:

  • 您可以 1. 声明一个 (IllegalState)Exception 变量。 2. 将 try/catch 包含在 do 循环中。 3. 分配您的异常变量。到 a) null 在 'songEnded = 0;` 之后或在 catch 块中,到 b) 捕获的异常。 4. 最后用while (tmpException != null);
  • ..这个循环会重复,直到 exception==null ... 替代变量类型:boolean(!/byte,short,..;)
  • ..但如果您只想重试一次(n 次):您可以重复 try catch within (outer/first) catch (为此定义一个(抛出/捕获)方法,以最小化代码重复和n重试:通过n限制上述循环,并调用(内部)函数...)

标签: java android while-loop try-catch android-mediaplayer


【解决方案1】:

我认为最好的办法是将它包装在一个 while 循环中,并在 while 循环中添加一个条件来检查媒体播放器是否已启动。

例如:

    void playMediaPlayer() {

        MediaPlayer mediaPlayer = new MediaPlayer();
        
        while (!mediaPlayer.initialized) {
            try {
                mediaPlayer.start();
                mediaPlayer.initialized = true;
            } catch (IllegalStateException ignored) {
                // optionally wait some time before trying again
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    static class MediaPlayer {
        
        boolean initialized = false;
        
        public void start() throws IllegalStateException{
        }
    }

【讨论】:

    猜你喜欢
    • 2010-11-23
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 2015-06-21
    • 2015-03-31
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多