Live data from Hacker News

Unchecked Java: Say goodbye to checked exceptions

github.com

191–200 of 297 posts

Re: Unchecked Java: Say goodbye to checked exceptions

#191

Earlier quoted context omitted.

It feels like you're trying to use Exceptions as a way to steer your logic, otherwise why would you need to know why an operation failed to such detail? Your controller method cannot act differently on a DBConnectionerror or OutOfMemory error. Not to mention that exceptions cause developers to use them as control flow mechanisms. For example searching a user by id. If the database returns 0 records, is that reason to…

> otherwise why would you need to know why an operation failed to such detail? I'm not defining the errors like DBConnectionError or OutOfMemoryError - it's the framework/platform which defines them and throws/returns them. > But the reality is that the user not being there isn't exceptional. That depends. In some contexts it is not exceptional (getting user by ID given as an argument to webservice), in that case usi…

```

try {

        ...

    }

    catch (UserNotFoundException e) {

        // handle ...

    }
```

This is just bikeshedding, because the equivalent code in Rust would be. For example, if there's multiple lines in the try block, who exactly returned this error? Are there other errors I didn't handle? Are there unexpected error that I forgot to check. For example, the "get" function of arrays in many languages usually always return T. But this is actually a lie because the array might be empty. So by right, it should return Option. But exception based programming have basically created this illusion that its infallible. How many people check their array accesses?

```

match value {

Ok(ok)=> {...}

Err(UserNotFoundException(e)) = { handle }

e => return e

}

```

Which does look more complicated, but it scales way way better when you have multiple errors

> But it is pretty bad for truly exceptional cases (which are unlikely to be handled anyway).

But why should a language be designed for exceptional cases? Errors are not exceptional at all. In the above code, the actual code will actually look like this

```

let rows = db.get_rows(query)?; // returns Result, E1>

let first_row = rows.first()?; // returns Option

let user = first_row.to_user()?; // returns Result

return user

```

Exception-based language will have the same looking code, but then imagine what would happen if you try to figure out which functions return what. You have no other recourse other than to dig into the source code to find all the unchecked exceptions that it can throw.

Another example, how would an exception language write this code to get multiple rows from the db and map each row to its respective user.

```

// get_rows and to_user both can fail

let users :Vec = db.get_rows(query)?.map(|r|r.to_user()).collect::()?;

```

Re: Unchecked Java: Say goodbye to checked exceptions

#192

Earlier quoted context omitted.

i do...if i ever get an IOException all i have to do is end the app, no need to deal with it in any way different than an unchecked exception https://phauer.com/2015/checked-exceptions-are-evil/

Check the root message of this thread... if you use unchecked exceptions you either crash or you swallow all exceptions. Both are evil, and checked exceptions are the solution.

That's only possible if your code is 100% correct.

Sometimes, your logic is flawed. A condition occurs which you erroneously deduced not to be possible.

Unchecked exceptions are the necessary manifestation of these unforeseen errors. Catching them is pointless, what will you do with them? Dynamically fix the logic of your program? What can be the reasonable response to "index out of bounds", try a different index? [1]

Depending on the domain it may be appropriate to convert them indiscriminately to checked exceptions at module boundaries (e.g. requests within a server) -- but within said module it remains pointless to catch them. (This is a form of swallowing.)

In other domains, crashing is the correct behavior. The code cannot proceed correctly, it must abort.

Checked exceptions are appropriate only when the exception can be anticipated and thus planned for, ideally by code closest to where it is thrown.

[1] Actually there was a paper a long time ago that monkey-patching C code to return fake "null" data in response to out-of-bounds memory accesses actually resulted in the intended (i.e. correct) behavior in the majority of cases. But I digress.

Re: Unchecked Java: Say goodbye to checked exceptions

#193
Like the idea, but I probably won't use it. Yes, checked exceptions are annoying, but the correct place to fix them is the source. This compiler plugin blinds you. The ordinary ways to mitigate checked exceptions (wrapping them in unchecked exceptions) is ugly but its also explicit.

Note: I will try it, because maybe I'm wrong.

Re: Unchecked Java: Say goodbye to checked exceptions

#194

Like the idea, but I probably won't use it. Yes, checked exceptions are annoying, but the correct place to fix them is the source. This compiler plugin blinds you. The ordinary ways to mitigate checked exceptions (wrapping them in unchecked exceptions) is ugly but its also explicit. Note: I will try it, because maybe I'm wrong.

You still get warnings about checked exceptions from this plugin, so it's not entirely flying blind.

Re: Unchecked Java: Say goodbye to checked exceptions

#195

Earlier quoted context omitted.

> That bug should have been caught by tests, code reviews and good communication. There's a reason we have compile-time checks. If you think compile-time checks should be replaced with additional tests, code reviews and good communication, then you want a scripting language, not a compiled language. You do not wrap checked exceptions in an unchecked one... unless you are a really bad Java programmer.

i do...if i ever get an IOException all i have to do is end the app, no need to deal with it in any way different than an unchecked exception https://phauer.com/2015/checked-exceptions-are-evil/

A better example for IOException is network errors. If your socket dies, your code should attempt to reopen it! It should report to the user if it can't!

Moreover, it's good that code nearest the site where the exception is thrown handles the error, as only it has context for what's going on at the time. Code further up the stack won't have any clue what this random IOException might relate to.

If you're confident the IOExceptions can't occur under normal conditions -- say, you know the file has correct permissions, isn't being concurrently modified, etc. -- then, encode this belief by catching the IOException near to its origin and rethrowing as an unchecked exception.

This same pattern shows up even in languages without exceptions. In C -- always check errno; don't try to catch SIGSEGV or SIGABRT; raise SIGABRT if errno is something you don't plan to handle. In F# -- you're forced to match Ok/Error; don't try to catch exceptions; raise an exception if you don't expect Error.

Re: Unchecked Java: Say goodbye to checked exceptions

#196
post #136

Earlier quoted context omitted.

> One of the biggest flaws in C#, in my experience, is lack of checked exceptions. I couldn't disagree more. Checked exceptions in Java have ruined a generation of programmers. The truth is, under checked exceptions, to satisfy the compiler the function that you called would declare that it throws a SomeModuleException and the programmer who wrote that function would put all his code in try/catch block that catches a…

You’re both right and wrong. Checked exceptions slow down development, make code ugly and in my theoretical opinion are an anti-pattern that should never be used. However in small to mid sized enterprise software companies with average developer talent it’s important to keep boundaries (and blame) clear. In the scenario in question, the CTO will blame OP and make them work the weekend to diagnose/fix it, so wrapping…

I put Java's popularity down to good support for Corporate-Oriented Programming ;)

Re: Unchecked Java: Say goodbye to checked exceptions

#197
post #117

Earlier quoted context omitted.

Lets be honest. The more likely thing is that either the coworker would use an unchecked exception or that they would change the callsite to: try { theUpdatedFunction(); } catch (MyNewCheckedException e) { logger.warn("Whoopsie doopsie", e) throw new SomeUncheckedException("Something failed, idk", e) } Which really is a zero sum game. The code still breaks the same way, but the checked exception gets eventually wrapp…

> That bug should have been caught by tests, code reviews and good communication. There's a reason we have compile-time checks. If you think compile-time checks should be replaced with additional tests, code reviews and good communication, then you want a scripting language, not a compiled language. You do not wrap checked exceptions in an unchecked one... unless you are a really bad Java programmer.

> You do not wrap checked exceptions in an unchecked one... unless you are a really bad Java programmer.

I disagree -- this is the correct thing to do if you believe it is not possible for the checked exception to occur. (Catching it is wrong -- what would you do to correct something which you believe not to be possible? Forcing the caller to handle it is wrong -- if you don't know what to do with it, they sure won't!) Wrapping checked as unchecked encodes your belief that should it occur, it is a logic error, akin to out-of-bounds array access or null pointer dereference.

(Of course, swallowing expected exceptions one is simply too lazy to do anything about is poor practice! Not disagreeing with that.)

Re: Unchecked Java: Say goodbye to checked exceptions

#198
post #129

Earlier quoted context omitted.

How would you define f in a different language such that f(g()) worked? You couldn’t do that in Go, for instance.

Simple! You just make f take in g's result type.

... not sure if serious or not

Re: Unchecked Java: Say goodbye to checked exceptions

#199
post #28
post #20

Exception based error handling is so bad and unsafe that adopting functional error handling with Either, Try etc as implemented by functional addon libraries for many languages, while not yet common, in time it will become the new default even in OO languages. (just like it's been the default in functional languages for decades) Functional error handling types are much simpler, safer and more powerful. Simpler becaus…

Checked exceptions are exactly analogous of Result/Either types. They are just built into the language with syntactic sugar, automatically unwrap by default (the most common operation), can be handled on as narrow or wide scope as needed (try-catch blocks), does the correct thing by default (bubbling up), and stores stack traces ! In my book, if anything, they are much much better! Unfortunately they don’t have a fla…

To my mind the big issue with existing examples of checked exceptions is that the language to talk about the exceptions is woefully inadequate, so it stops you from writing things that would be useful while dealing correctly with exceptions. The go-to example is a map function, which we should be able to declare as throwing anything that might be thrown by its argument. Without that we need to either say that map might throw anything and then handle cases that actually can't happen, suppress/collect exceptions inside map, or suppress/collect errors inside the functions we're passing to map, all of which add boilerplate and some of which add imprecision or incorrectness. It would also be good to be able to state that a function handles some exceptions if they are thrown by its argument. And all of this should be able to be composed arbitrarily. And... somehow not be too complicated. For usability, it should probably also be possible to infer what's thrown for functions that are not part of an external API.

Re: Unchecked Java: Say goodbye to checked exceptions

#200

Earlier quoted context omitted.

Simple! You just make f take in g's result type.

... not sure if serious or not

I'm completely serious in the sense that you could do that and really would in some situations.

You might do it because you want to factor the handling of the different result cases out to another function.

Post reply on HN