当前位置:网站首页>On kotlin's checked exception mechanism

On kotlin's checked exception mechanism

2020-12-07 21:15:37 Guo Lin

This article is also published in my WeChat official account. , Scan the QR code at the bottom of the article or search on wechat Guo Lin Can focus on , Article updates every weekday .

Now use Kotlin Of Android There are more and more developers .

The language was ignored from the beginning , To become Android First level language developed , To the later Google Guan Xuan's Kotlin First.Kotlin Is being accepted and recognized by more and more developers .

A lot of learning Kotlin We've learned about it before Java Of , And itself Kotlin It's based on JVM Language , So it's inevitable to have to talk to Java Compare .

Kotlin Many characteristics of , Familiarity Java It seems that , Some people like , Some people don't like . But even those who don't like it , Once it's done Kotlin After program development , It's hard to escape the true fragrance law .

Today I want to talk to you about the topic , yes Kotlin One of the more controversial features in the early days :Checked Exception Mechanism .

because Kotlin To cancel the Checked Exception, It's in a lot of Java Developers seem totally unacceptable , Maybe a lot of Java Supporters refuse to use Kotlin Why . But at the moment, Kotlin Has been Google It's been more than two years since I became a full-time official , Developed thousands of Android application . You'll find that , Even without Checked Exception,Kotlin There is no program like Java More questions , So in programming languages, for Checked Exception It may not be as necessary as many people think .

Of course , In this article, I can not give a conclusion to prove who is right and who is wrong , More is to talk about my own views and personal experience , In addition, I quote some authoritative opinions of big men .

in addition , There is always no right answer to this question , Because there is no best programming language in the world (PHP With the exception of ). Each programming language has its own set of theories and logic to choose different processing methods , So instead of arguing Java Medium Checked Exception Is the mechanism redundant , It's better to demonstrate Kotlin There is no Checked Exception Why is the mechanism reasonable .

that , We start with what is Checked Exception Start talking about .

Checked Exception, abbreviation CE. It is a mechanism introduced by programming language to ensure that the program can handle and catch exceptions better .

To be specific , When a method calls another interface that may throw an exception , Or catch this exception , Or throw the exception , Give it to the next layer to capture .

be familiar with Java Language friends are no stranger to this mechanism , Because we write programs almost every day under the influence of this mechanism .

Look at the following code :

public void readFromFile(File file) {
    FileInputStream in = null;
    BufferedReader reader = null;
    StringBuilder content = new StringBuilder();
    try {
        in = new FileInputStream(file);
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            content.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 Copy code 

This code is for each Java Programmers should be familiar with , This is a paragraph. Java File stream operation code .

We have a variety of potential exceptions that may occur when we perform file stream operations , So these exceptions have to be caught or thrown , Otherwise, the program will not compile through , This is it. Java Of Checked Exception Mechanism .

With Checked Exception, We can ensure that our program will not have some hidden potential exceptions , otherwise , These anomalies are like time bombs , It could detonate our program at any time .

It seems ,Checked Exception It's a very necessary mechanism .

Kotlin There is no Checked Exception The mechanism , This means that we use Kotlin When performing the above file stream operation , Even if you don't catch or throw an exception , It can also be compiled normally .

be familiar with Java Do you think the developers are so insecure ?

So let's try to analyze and think about , Why? Kotlin There is no Checked Exception.

I'm learning Kotlin when , It is found that the language has referenced some of the industry's best programming practices in many aspects of its design .

for instance ,《Effective Java》 It is mentioned in this book that , If a class is not designed specifically for inheritance , Then we should declare it as final, Make it unenheritable .

And in the Kotlin among , A class is not inheritable by default , Unless we take the initiative to declare it as open.

There are many, many, many similar examples .

therefore ,Kotlin Cancel Checked Exception And it's certainly not a random decision , It's supported by a lot of theories .

for instance ,《Thinking in Java》 The author of Bruce Eckel It has been publicly stated that ,Java In language Checked Exception It was a wrong decision ,Java It should be removed .C# The father of Anders Hejlsberg I agree with this view , therefore C# There is no Checked Exception Of .

So most of us Java Developers think it's very necessary Checked Exception What's wrong with the mechanism ?

These big guys cite many reasons , But I think the main reason is actually one of the reasons : trouble .

Checked Exception Although the mechanism improves the security of programming language , But sometimes it makes us crazy when we write code .

because Checked Exception The existence of mechanisms , For some code with potential exceptions , We have to deal with it . There are only two ways to deal with it : Or use try catch The code block catches the exception , Or use throws Keyword throws an exception .

Take the file stream operation as an example , We used it twice try catch Code block for potential exception capture , But in fact, it is more just to satisfy the compiler :

public void readFromFile(File file) {
    BufferedReader reader = null;
    try {
        ...
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 Copy code 

This code is in Java Among them is the most standard and standard writing method , But you will find , Few of us can be in catch What meaningful logical processing is written in , It's usually just a print of the exception information , Inform the stream that an exception has occurred . So what to do if the stream is abnormal ? No one knows what to do , In theory, the upper class should always work .

Think about it , Are you in close File stream try catch It's just to make the compiler pass ? You are close Has there been any meaningful logic handling in exception trapping of ?

and Checked Exception The existence of the mechanism forces us to handle these uncapped exceptions , Even if we clearly don't want to deal with it .

The design idea of this mechanism is good in itself , But it also indirectly created a lot of cramming code , Just to satisfy the compiler to program , It leads to writing a lot of meaningless try catch sentence , Make the project code look more bloated .

So if we choose not to catch exceptions , But throw the exception up ? The fact proved that , It may not be a particularly good idea .

most Java Programmers should have used reflective API, Writing reflection code is a little annoying , It's its API It throws a lot of exceptions :

Object reflect(Object object, String className, String methodName, Object[] parameters, Class<?>[] parameterTypes)
	    throws SecurityException, IllegalArgumentException, 
		IllegalAccessException, InvocationTargetException, 
		NoSuchMethodException, ClassNotFoundException {
	Class<?> objectClass = Class.forName(className);
	Method method = objectClass.getMethod(methodName, parameterTypes);
	return method.invoke(object, parameters);
}

 Copy code 

Here I just wrote the simplest reflection code , Unexpectedly 6 An exception is waiting for me to deal with . I can't fully understand what each of these anomalies means , Instead of writing a lot of try catch Code , It's better to throw all the exceptions to the next level , So the code looks a little cleaner .

You think so , That's what people on the upper floor think , Even more egregious , He may also be based on the exception you throw , Add a little more exceptions and keep throwing them up .

According to my information , Some projects go through such layers of accumulation , Calling an interface even requires capturing 80 Multiple exceptions . I think the person who calls this interface must be scolding her . You think in this case , Can he patiently handle every exception type carefully ? Absolutely impossible , Maybe he'll just catch A top-level Exception, Include all the anomalies , So as to thoroughly let Checked Exception The mechanism is meaningless . Or, , He may add a fire to the current exception throw chain , To throw 100 An exception contributes ...

In the end, we can see that ,Java Of Checked Exception Mechanism , The original intention of the design is really good , And it's advanced , But it has a high coding standard for programmers . The designer of each layer of methods should be able to clearly identify which exceptions should be caught internally , Which exceptions should be thrown up , So that the entire stack and method call are within a reasonable range .

However, the more regrettable reality is , Most programmers can't do it , Abuse and inert use CE Mechanisms are widespread , Not at all Java Design the desired effect of this mechanism , This is also Kotlin Cancel Checked Exception Why .

many Java Programmers are more worried about this ,Kotlin To cancel the Checked Exception Mechanism , Doesn't that make my program dangerous ? Whenever I call a method , I have no idea what exception this method might throw .

First of all, the answer to this question has been given at the beginning , After more than two years of practice, it has been found that , Even without Checked Exception,Kotlin There is no program developed like Java There are more exceptions in the developed program . On the contrary ,Kotlin Instead, the program reduces a lot of exceptions , because Kotlin Added the function of handling null pointer exception at compile time ( Null pointer has always been at the top of the crash rate of all languages ).

So as to why it's cancelled Checked Exception It doesn't cause more exceptions in the program , I'd like to break it down into the following points .

First of all ,Kotlin It doesn't stop you from catching potential exceptions , It's just that you're not required to capture it .

Experienced programmers write programs , In fact, most of the places that are most likely to be abnormal are well known . For example, I'm writing network request code , Because of the instability of the network , Failure of a request is highly likely to happen , So even if there is no Checked Exception, Most programmers also know that you should add a try catch, Prevent program crash due to network request failure .

in addition , When you are not sure if there is a potential exception thrown when you call a method , You can always open this method , Observe its throw statement to determine . Whether you have the source code of this class or not, you can see what exceptions are thrown by each method of this class :

public class FileInputStream extends InputStream {

    public FileInputStream(File file) throws FileNotFoundException {
        throw new RuntimeException("Stub!");
    }

    public int read(byte[] b, int off, int len) throws IOException {
        throw new RuntimeException("Stub!");
    }

    public void close() throws IOException {
        throw new RuntimeException("Stub!");
    }
    ...
}

 Copy code 

And then when you feel like you need to catch this exception , And then capture it , You can still follow before Java The way to catch exceptions in Kotlin Code , It's just that there's no mandatory requirement , You are free to choose whether to capture and throw .

second , Most methods don't throw exceptions .

It's a fact , Otherwise you will never fall in love with Checked Exception Mechanism , They curse it every day .

Just imagine , If you write every line of code , Every method called , We have to deal with it try catch Just capture it , Do you want to break the keyboard ?

The situation I'm talking about is Java There's really a very typical example , Namely Thread.sleep() Method . because Thread.sleep() Method throws a InterruptedException, So every time we call this method , You have to use try catch Capture it :

public class Main {
    
    public void test() {
        
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
    }
    
}

 Copy code 

That's why I really don't like this method , It's just a word to use : Bother .

in fact , Maybe most of them Java Programmers don't even know why to catch this exception , Only the compiler reminds me that I have to capture .

The reason why we're calling Thread.sleep() Method, you need to capture InterruptedException, It is because if during the current thread sleep , We interrupt the sleeping thread in another thread ( call thrad.interrupt() Method ), that sleep() Method will end hibernation , And throw a InterruptedException. This kind of operation is very rare , But because of Checked Exception The existence of , Each of us needs to pay for this rare operation : Every call Thread.sleep() When the method is used , I have to write a long paragraph try catch Code .

And by the Kotlin among , You will no longer hate to use Thread.sleep() Method , Because there is no Checked Exception, The code has become fresh :

class Main {

    fun test() {
        
        Thread.sleep(1000)
        
    }

}

 Copy code 

Third , Have Checked Exception Of Java It's not that safe .

Some people think that ,Java Owned by Checked Exception Mechanism , You'll feel at ease with every method you call , Because you know what exception it's going to throw . But not Checked Exception Words , Call any method, I have no idea .

So is that reasonable ? Obviously it's not true . Otherwise , Yours Java The program should never crash .

in fact ,Java All the exception types are divided into two categories : Checked anomalies and undetected anomalies . Only checked anomalies are subject to Checked Exception The constraints of mechanism , Unchecked exceptions do not force you to catch or throw exceptions .

for instance , image NullPointerException、ArrayIndexOutOfBoundsException、IllegalArgumentException These are all unexamined anomalies , So even if there is a null pointer in the method you call 、 Array out of bounds and other abnormal risks ,Checked Exception The mechanism doesn't require you to capture or throw .

thus it can be seen , Even if Java Have Checked Exception Mechanism , It doesn't guarantee that every method you call is safe , And I think null pointers and array overruns are much more unusual than InterruptedException Such anomalies are more common , but Java It's not protected .

as for Java How to classify which exceptions belong to the checked exception , Which are undetectable anomalies , I'm not sure about that either .Java Our design team must have its own theoretical basis , It's just that this theory doesn't seem to be accepted by designers of other languages .

therefore , You can probably understand it as ,Kotlin It is to further simplify the exception type , Classify all exceptions as undetectable , That's it .

therefore , What's the final conclusion ?

unfortunately , There is no conclusion . Just as everything has its diversity , About Checked Exception On this question , There is no unified conclusion .

Java Have Checked Exception The mechanism is not wrong ,Kotlin Cancel Checked Exception The mechanism is not wrong . I think that's the conclusion you can draw after reading this article .

however , I hope you'll be , In the use of Kotlin When programming programs , Don't worry about whether there is Checked Exception What's the problem .

If you want to learn Kotlin And the latest Android knowledge , You can refer to my new book 《 First line of code The first 3 edition 》, Click here for details .

版权声明
本文为[Guo Lin]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201207191521761m.html