FurkanTekno
FurkanTekno

Reputation: 31

How can I add a try and catch in java

I have a Webview in Java. Being a newview wondering how can I add a try and catch here? Please help me

 myWebView = (WebView) findViewById(R.id.webview);
 WebSettings webSettings = myWebView.getSettings();
 webSettings.setJavaScriptEnabled(true);
 myWebView.loadUrl("http://www.gymnasiumebingen.de");
 myWebView.setWebViewClient(new WebViewClient());

 myWebView.setDownloadListener(new DownloadListener() {
     public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
         Intent i = new Intent(Intent.ACTION_VIEW);
         i.setData(Uri.parse(url));
         startActivity(i);
      }
  });
}

@Override
public void onBackPressed () {
    if (myWebView.canGoBack()) {
        myWebView.goBack();
    } else
        super.onBackPressed();
    }
 }

Upvotes: 1

Views: 85

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26460

I'll give you an example

@Override
    public void onBackPressed () {
        if (myWebView.canGoBack()) {
            try {
                // protect code that may fail
                myWebView.goBack();
            } catch(Exception ex) {
                // write some code to mitigate
                // the failure
            } 
        } else
            super.onBackPressed();
    }

You can do that around any piece if code that might throw an exception. This catches all possible exceptions but you can even catch targeted ones.

Bear in mind that it will not protect the listener code if you surround the declaration. You need to put a try catch around the listener code

Upvotes: 1

Related Questions