2015-10-25 208 views
1

我尝试使用try和catch块创建android一种方式来处理没有互联网连接或如果web服务器关闭。在日食IOException红色下划线。如果http://192.168.0.23/loc/index.php的加载失败,则应该加载"file:///android_asset/myerrorpage.html"。我知道只尝试和从PHP抓住,并已看过其他任何教程,但无法找到我的错误。尝试和捕获url连接错误

它显示以下消息:为IOException的

无法到达catch块。此异常不会从try语句体抛出

我的代码:

@Override 
public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_localy); 
    mWebView = (WebView) findViewById(R.id.webview); 
    // Brower niceties -- pinch/zoom, follow links in place 
    mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); 
    mWebView.setWebViewClient(new GeoWebViewClient()); 
    // Below required for geolocation 
    mWebView.getSettings().setJavaScriptEnabled(true); 
    mWebView.getSettings().setGeolocationEnabled(true); 
    mWebView.setWebChromeClient(new GeoWebChromeClient());  
    // Load google.com 
    try { 
    mWebView.loadUrl("http://192.168.0.23/loc/index.php"); 
    } 
    catch (IOException e) { 
     mWebView.loadUrl("file:///android_asset/myerrorpage.html"); 

    } 
} 

回答

1

loadUrl不会引发IOException

公共无效使用loadURL(字符串URL)

负载t他给了URL。

参数
网址资源的URL加载

这就是为什么你不应该试图捕获IOException(你也只能望尘莫及可以由try块的代码中抛出异常)。

只需更换用一个语句整个try-catch块:

mWebView.loadUrl("http://192.168.0.23/loc/index.php"); 

至于如何在URL的负载检测错误,上面的链接包含此代码示例:

webview.setWebViewClient(new WebViewClient() { 
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { 
    Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show(); 
    } 
}); 
webview.loadUrl("http://developer.android.com/"); 

因此,将其调整到您的代码:

mWebView.setWebViewClient(new WebViewClient() { 
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { 
    mWebView.loadUrl("file:///android_asset/myerrorpage.html"); 
    } 
}); 
mWebView.loadUrl("http://192.168.0.23/loc/index.php"); 

我没有,虽然进行了测试。

+0

这工作,如果没有互联网连接可用,但在可用互联网的情况下,webview只显示index.php。如果index.php有一个重定向错误页面显示。 – Droidboyx

2

IOException的无法到达catch块。

try { 
mWebView.loadUrl("http://192.168.0.23/loc/index.php"); 
} 
catch (Exception e) { 
    Log.d(e.getMessage()); //Get the Exception thrown. 
    mWebView.loadUrl("file:///android_asset/myerrorpage.html"); 

} 

你:这个异常从来没有从try语句体

意味着,你把你的try代码不会触发任何IOException试图把Exception e如下抛出会知道你得到了什么异常。

+0

为什么你将我的答案没有标记为正确的,没有工作? –

+0

我的答案不适合你吗?我应该更新我的答案吗? –