简体   繁体   中英

How to add try/catch in kotlin code using android studio?

I have to add try/catch in my kotlin code while using android studio,but do not understand how to add this. Below are the codes where I have to add try/catch.

I did not try anything yet because I am totally confused where to apply 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()
            }
        }
    }

}

2.

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)
        }

    }
}

I expected "SMS received Toast message", but I get "Unfortunately,Application is stopped" and crashes..

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()  
           }
}

you should be applying the try catch over code which can throw exceptions. for the code you posted, there are a few places where it could potentially crash, such as index out of bounds ( sms[i] ) or if ( extras.getString("pdus" ) fails to find this key, hence my solution wraps both of these in the same try catch, what you then do with the exception is up to you.

if you want to handle more specific exceptions, you can also do this:

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
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM