[Kotlin] Catch Error in Java

For example you have the Java class:

package com.rsk.java;
import com.rsk.kotlin.Customer;
import com.rsk.kotlin.CustomerDatabase;

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Customer phil = new Customer(0, "Phil");
        CustomerDatabase db = new CustomerDatabase();
        List<Customer> customers = db.getCustomers();
        try {
            customers.add(phil);
        } catch (IllegalAccessException e) {
            System.out.println(e);
        }
    }
}

 

If you have used kotlin, need to add @Throw to tell java, that fun might throws:

package com.rsk.kotlin

data class Customer (val id: Long, val name: String)

class CustomerDatabase() {
    val customers = listOf(
            Customer(1, "Matti"),
            Customer(2, "James"))

    @Throws(IllegalAccessException::class)
    fun addCustomer(c: Customer) {
        throw IllegalAccessException("You cannot add a customer")
    }
}

 

posted @ 2020-10-21 01:46  Zhentiw  阅读(95)  评论(0)    收藏  举报