Monday, October 17, 2016

What is java try catch

In a running java program an error could occurs at unexpected time. For example, when you are browsing to internet, you post a status or a message, at that time the internet connection is off. The piece of code that running that post task should be aware of this. So, how do the code handle this unexpected error in a running program?. The answer is they use try catch statement in their program.
When this error occurs the code execute the piece of code in catch statement rather than force close the entire running app that will make user annoyed. let's see a piece of code containing a try
catch statement.
package com.example.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

public class MainActivity extends Activity {
    private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            button = (Button) findViewById(R.id.btnLogin);
        }
        catch (Exception e) {
            e.printStackTrace();
            Log.e("Exception raised", e.toString());
        }
        

    }
}

Look at the line 14 to line 20, we have put a try-catch statement here. The purpose of this statement is to anticipate if an exception will be raised inside the try statement, in this example at line 15. This exception will be raised for example if findViewById(R.id.btnLogin) return object not a Button type.
So what happened then if it is not Button type?. The code will immidiately jump to catch statement at line 18. If the exception is not raised, the code at line 18 to 19 will never be executed. Now at line 18 you can put a debug breakpoint to see what makes the cast exception appears. By knowing the cause of the exception, you can fix the code later and minimize the bug in your code.


Thank you for visiting our website. Just comment below if you have any question to ask.

No comments:

Post a Comment