Home > database >  I'm not able to pass value inside BaseException constructor. Why?
I'm not able to pass value inside BaseException constructor. Why?

Time:03-29

BaseException

class BaseException(private val classname: String) : Exception() {

    override fun setStackTrace(stackTrace: Array<out StackTraceElement>) {
        val trace = arrayOf(StackTraceElement(classname, "methodNameOfExe", classname, 10))
        super.setStackTrace(trace)
    }
}

TestClass

{
....

    override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, viewType: Int) {
            try {
                setOnBindViewHolder(viewHolder, viewType)
            } catch (e: BaseException("Test")) { //compiler error for BaseException constructor
               ....
            }
        }

...

Compiler error is coming, if I'm trying to pass String arg

CodePudding user response:

That's not the correct way of doing it, you can't pass through parameters when assigning types.

take the following as example:

val foo : String  

here, i'm specifying that my variable foo is of type String, right ? That's exactly what this statement is doing as well :

catch (e: Exception)

you're saying that e is of type Exception, you can't create a new instance here.

that means that you should change your code to be something like this:

catch (e: BaseException) {}

and then where you need to use this, you'd do something like:

throw BaseException("Test"))
  • Related