如何使用 Android Studio 在 Kotlin 代码中添加 try/catch?

问题描述 投票:0回答:1

在使用 Android Studio 时,我必须在 Kotlin 代码中添加 try/catch,但我不明白如何添加它。下面是我必须添加 try/catch 的代码。

我还没有尝试任何东西,因为我完全困惑在哪里应用 try/catch。

1.

class SmsReceiver : BroadcastReceiver(){
    override fun onReceive(context: Context?, intent: Intent) {

        val extras = intent.extras

        if(extras != null){

            val sms: Array<Any> = extras.getString("pdus") as Array<Any>

            for(i in sms.indices){
                val format = extras.getString("format")

                var smsMessage = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    SmsMessage.createFromPdu(sms[i] as ByteArray,format)
                }else{
                    SmsMessage.createFromPdu(sms[i] as ByteArray)
                }

                var phoneNumber = smsMessage.originatingAddress
                val messageText = smsMessage.messageBody.toString()

                Toast.makeText(context,"$phoneNumber:(Private)\n" + "messageText: $messageText",Toast.LENGTH_SHORT).show()
            }
        }
    }

}
class MainActivity :AppCompatActivity(){

    private val requestReceiveSms: Int = 3

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if(ActivityCompat.checkSelfPermission(this,android.Manifest.permission.RECEIVE_SMS) !=
            PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.RECEIVE_SMS),
                requestReceiveSms)
        }

    }
}

我期望“短信收到 Toast 消息”,但我得到“不幸的是,应用程序已停止”并崩溃......

android kotlin try-catch
1个回答
7
投票

用途:

try {
    if(extras != null) {

        val sms: Array<Any> = extras.getString("pdus") as Array<Any>

        for(i in sms.indices) {
            val format = extras.getString("format")

            var smsMessage = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                SmsMessage.createFromPdu(sms[i] as ByteArray, format)
            }
            else {
                SmsMessage.createFromPdu(sms[i] as ByteArray)
            }

            var phoneNumber = smsMessage.originatingAddress
            val messageText = smsMessage.messageBody.toString()

            Toast.makeText(context, "$phoneNumber:(Private)\n" + "messageText: $messageText", Toast.LENGTH_SHORT).show()
        }
    }
}
catch (ex: Exception) {
   // Your error handling code here
   // Here, consider adding Log.e("SmsReceiver", ex.localizedMessage)
   // This log statement simply prints errors to your android studio terminal and will help with debugging, alternatively leave it out
    if (context != null) {
        Toast.makeText(context!!, ex.localizedMessage, Toast.LENGTH_SHORT).show()
    }
}

您应该对可能引发异常的代码应用 try catch。对于您发布的代码,有一些地方可能会崩溃,例如索引越界(

sms[i]
)或如果(
extras.getString("pdus"
)无法找到此密钥,因此我的解决方案将这两个都包装在同样的尝试捕获。然后,您如何处理例外情况取决于您。

如果你想处理更具体的异常,也可以这样做:

try {
    if(extras != null) {

        val sms: Array<Any> = extras.getString("pdus") as Array<Any>

        for(i in sms.indices) {
            val format = extras.getString("format")

            var smsMessage = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                SmsMessage.createFromPdu(sms[i] as ByteArray, format)
            }
            else {
                SmsMessage.createFromPdu(sms[i] as ByteArray)
            }

            var phoneNumber = smsMessage.originatingAddress
            val messageText = smsMessage.messageBody.toString()

            Toast.makeText(context, "$phoneNumber:(Private)\n" + "messageText: $messageText", Toast.LENGTH_SHORT).show()
        }
    }
}
catch (indexOutOfBoundsException:IndexOutOfBoundsException) {
   // Your error handling code here
}
catch (nullpointer : NullPointerException) {
  // Your error handling code here
}
© www.soinside.com 2019 - 2024. All rights reserved.