android - 尝试捕捉 : Is it OK to leave applications with handled exceptions?

标签 android exception android-edittext

我对编程还很陌生,所以有些东西我是通过观察学到的,但还没有完全理解。 Try-Catch 就是其中之一。根据我的研究,try 语句允许我定义一个代码块来测试错误,而 catch 语句允许我定义一个代码块,如果 try block 中发生错误则执行。

我明白了。我曾尝试在收到导致应用程序崩溃的异常错误的情况下使用 Try-Catch。 Try-Catch 似乎可以防止(停止)崩溃。但这是我的问题,有一个不断捕获异常错误的应用程序可以吗?

例如,我正在使用 EditText 小部件。我希望 EditText 的输入值代表货币,所以我应用了 android:inputType="numberDecimal"。我从中了解到的问题是此属性允许小数点后的任意数量的值。这是我想出以适当的格式以编程方式更新 EditText 的想法,使用诸如 DecimalFormat 之类的东西。

我不会发布我的全部代码,但这是我很好奇的部分。

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        // TODO Auto-generated method stub

        DecimalFormat format = new DecimalFormat("0.00");

        if (etBill.getText().toString() != null && 
                etBill.getText().toString().length() > 0) {
            try {
                doubleBill = Double.parseDouble(etBill.getText().toString());
                strFormatted = format.format(doubleBill);
                Log.d(TAG, "unformatted(" + doubleBill + ")" + 
                        " // formatted(" + strFormatted + ")");

                //etBill.setText("$" + strFormatted, TextView.BufferType.EDITABLE);
                etBill.setText("$" + strFormatted);
            } catch (NumberFormatException nfe) {
                Log.e(TAG, "FloatingPointParser.parseDouble error");
            }
        } else {
            // values in editText were deleted; hardcode value
            doubleBill = 0.0;
            strFormatted = format.format(doubleBill);
        }

    }

这是我每次向 EditText 小部件输入值时捕获的异常错误。

enter image description here

所以我的问题是,Try-Catch 是我纠正错误的方法吗?在应用程序运行的整个生命周期中捕获异常错误(例如 NumberFormapException)是否可以?我用对了吗?提前致谢!

最佳答案

NumberFormatException 是一个运行时异常,您正在正确捕获它。然而,不是仅仅打印一些东西让您知道您已经捕获到它,您应该通过重新运行您的代码来处理它,或者将异常传递到堆栈中。例如,如果用户输入一个数字然后捕获到此异常,您可以提示他们重新输入一个新数字。如果抛出此异常的数字不是由用户提供,而是由您的代码提供,则表明您在某处存在逻辑错误,应该修复该错误以防止首先抛出此异常。

关于android - 尝试捕捉 : Is it OK to leave applications with handled exceptions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20822120/

相关文章:

android - 如何使用 onPreviewFrame() 中的 byte[] 数据在肖像中使用 OpenCV 人脸检测?

android - 触摸行的容器 UI 元素时突出显示 ListView 行

android - 使用 HttpUrlConnection 的 Volley 请求

Frame.add(Object) 处的 java.lang.NullPointerException

.net - 防止 Visual Studio 中断未处理的异常

javascript - 在引导的 Firefox 扩展中设置全局错误处理程序

android - 带有长标签的布局表单

Android paddingBottom 在没有 paddingTop 的情况下无法正常工作

android - 如何从 edittext 中的 drawable 中删除色调颜色?

android - 如何同时拥有 singleLine ="false"和 imeOptions ="actionNext"用于 EditText?