Why do we throw exceptions?

Question from blindspot23#4418

Why do we throw an exception when try and catch can handle it?

The use case is for "exceptional conditions". Like if you write a library that asks google for search results that can always fail because it goes over the network and you use try catch to handle it, but sometimes either

  1. you can't handle it and you need to crash
  2. you don't want to handle it and prefer to crash
  3. It makes sense to "bubble" the exception up multiple layers

Making it more complicated - there are actually 2 "kinds" of exceptions in Java, checked and unchecked ones.

Checked exceptions like IOException you always have to handle either by doing some behavior or rethrowing.

Unchecked exceptions like RuntimeException the language doesn't make you handle so generally those are used for situations where you don't think people will want to try to recover.

It's all also really abstract until you try writing some code that uses or works with them. (and also really frustrating because not even the standard library does exceptions "right" always)

<- Index