Chapter:Exceptions - What is it

From Juneday education
Jump to: navigation, search

Meta information about this chapter

Expand using link to the right to see the full content.

Introduction

This chapter introduces the exceptions mechanism of the Java language and runtime system. It addresses the two main types of exceptions, runtime exceptions and checked exceptions. On a basic level, the chapter also discusses when we could use runtime exceptions and when we might use checked exceptions and what the consequences are of the respective choice.

The chapter also introduces the creation of custom exceptions and chaining constructions (wrapping a cause exception inside another exception).

Purpose

The purpose of this chapter is to prepare the students for the assignments and for follow-up Java courses. The Java API is full of methods which throws checked and unchecked exceptions, so the students will pretty soon be forces to handle-or-declare when using many API classes, such as classes for I/O.

Rather than just giving the students template code for try-catch-finally, we aim to give the students a broader understanding of why exceptions are thrown. This is an introductory Java book so we don't go very deep into design decisions, but we try to at least inspire the students to think about where to handle exceptions and what the difference for client code is if we use runtime (unchecked) exceptions or checked exceptions.

Goal

The goal is that the students should have a solid base knowledge about exceptions in Java so that they can both write handlers for exceptions thrown by API code and also the basics for how to throw an exception programmatically. The students should, after the completion of this chapter have enough knowledge to solve the assignment 2 in which exceptions are used, as well as knowing what to do when they run into an API method which declares that it throws some exceptions. The students should also know the rules about handle-or-declare for checked exceptions, and what the concept of an unchecked exception is.

Instructions to the teacher

Common problems

There are a lot of misconceptions about exceptions floating around which we will try to counter in this chapter. One misuse of exceptions is the practice of writing a handler (a catch-clause) which doesn't do anything or at most prints something. Some IDEs actually make this situation a practice for beginners, when they detect a call to a method which throws a checked exception and adds a try-block around the call and a catch-block which catches the exception and does nothing to handle it.

Students may be tempted to write try-catch with a meaningless catch-block, just to get rid of a compiler error complaining about some checked exception which needs to be handled (or declared).

Try to help the students understand the thought behind exceptions and that exceptions can be a valuable tool to make a robust system. Also, try to get the students think about the difference between programmer errors (which may trigger runtime exceptions) and contingencies which can be handled and signaled through the use of checked exceptions.

The students may have a difficult time taking in the full picture and discussion, since they haven't yet seen code for a larger system which uses tiers for instance. The students will probably need to read the explanatory texts a few times, see the lectures a few times and do the exercises before they start to comprehend exceptions on a deeper level. It is OK if the students of this introductory course get a more shallow understanding about exceptions and focus more on the rules and syntax.

If they know how to handle-or-declare a checked exceptions, that's an important first step towards a deeper discussion, which might come in a later course or a book on more advanced topics. Make sure that the students at least understand the semantic and syntactic differences between unchecked and checked exceptions. The exercises for the "Writing your own exceptions" might be useful for a discussion on when we can use checked exceptions and when we can use unchecked (runtime) exceptions.

The idea of those exercises is, using a class for a bank account as an example, to show that trying to withdraw a too great amount is a contingency which can be signaled using a custom checked exception and declaring the withdraw method with a throws declaration. This will force the client code (methods calling withdraw on some account object) to prepare for the case that a withdrawal might be denied because of lacking funds.

The bank account class has to deal with some other potential problems too, like some programmer trying to create an account with an initial amount with a negative value. This should not be allowed, and here the class uses a runtime exception to abort such operations. The constructor, deposit and withdraw methods all may throw a runtime exception is some client code doesn't behave and only use positive numbers (or zero) when calling them. Using a runtime exception to abort a faulty call to deposit violating the rule that only positive amounts (or zero) are legal, doesn't create the need for handle-or-declare which is good for all well-behaving clients. If you follow this rule, the reward is that you don't need to handle-or-declare, since we are using runtime exceptions. The methods will, however, punish code in violation with this simple rule with a runtime exception (which must be handled at some level, or the code will crash the application).

We introduce the idea that crashing because of bugs sometimes is preferable to just silently handle buggy operations. A crash at least lets us detect the problem and fix the bug. This might be a hard concept for the students to grasp, but at least we try to make them reflect on this.

Videos

Videos for Exceptions - what is it?

Look ahead! Videos for all the exception chapters

All videos for the exception chapters:

See individual chapters for individual links to the videos.

Full frontal - Code up front!

Here's a small code example, showing what code which handles exceptions look like. You're not expected to understand it, we just want to show you some code early on.

    // Code retrieving an account:
    SavingsAccount a = loadAccountFor("Henrik Sandklef");
    
    // Here, we try to withdraw some amount from the customer's account
    // But we know that could fail, if there's not enough balance
    try{
      a.withdraw(price);
    }catch(InsufficientBalanceException e){
      // Here we do something about the problem
      System.err.println("Couldn't withdraw: " + e.getMessage());
      notifyCustomer(e);
    }

Exceptions: What is an Exception

This chapter introduces the concept of an exception. An exception is a signal of your program's running into some situation which is not the normal case or what you hoped for.

You can think of exceptions as being of two types: Contingencies (eventualities which may occur but are not very normal) and failures which are when something goes very wrong.

A contingency is when something rare happens but we know that it could happen and should be prepared for it. If there is some rule in our system which is being broken, then we could use the exception mechanism of Java to signal that this rule was broken. If we think about that, passing information about this rule having been violated using an exception object, allows us to have a feedback mechanism from a method which doesn't use the return statement.

A method could have a return value for all normal conditions but when something rare happens, the method could instead throw an object of some exception type to the caller (the return statement would then never be reached and the method would not be possible to evaluate to any value - instead the caller would have to deal with the exceptional case that occurred).

This introduction also discusses in the video lecture that in Java, there are two main types of Exception objects. The first type is "checked exceptions" which are exceptions that a method could declare that it can throw, and that the compiler forces the calling code to handle using some special code (which we will show in a later lecture). A method which can "throw" an object whose type is a checked exception must either declare that it throws this exception, or handle it internally. If the method doesn't handle such exception and instead declares that they may be thrown from the method, any code which calls the method end up in the same situation.

If code in a method A calls method B, and method B is declaring that it might throw a checked exception, then the method A author must choose between two options: 1. Handle the exception which might be thrown by B, or, 2. declare that A too throws this exception.

These rules allow us to write code which "warns" for exceptional cases and force calling code to handle this or pass the problem on to some code which does handle it.

What could be a contingency exception (an eventuality which we know could happen but hope it doesn't)? Let's pretend we have a web shop which has some code for processing orders from the customers. The company has discovered that some orders look very suspicious and seem to come from the same customer but too quickly for being the result of a real human sitting in front of a web browser and actually placing the orders. The company then adds a business rule, that no two orders may be placed by the same customer within five seconds (because it must be a machine placing the orders rather than a human).

The method for processing orders must now obey this rule and check that an order is not placed by a customer who just placed an order less than six seconds ago. This should not be so frequent and could be considered a contingency. Let's further say that the method placeOrder(Order o) normally returns an int with the order number from the order database. How would we deal with the case of an order being denied because of the five second rule? We would declare that the method throws a checked exception. This would force the code calling processOrder(Order o) to write code which prepares for this situation. The processOrder(Order o) method would in turn have code which "throws" the exception if it finds that the rule is violated.

This all allows the code which calls processOrder(Order o) to focus on the normal case and getting the int signifying the order id from the order database. If the rule would be broken, the calling code includes code which will also deal with this exceptional case. The calling code would just deny and cancel the order, possibly giving the customer notice of this.

What about faults, then? Bad things which we expect (or hope) never will happen, is typically to be considered faults. Their reasons could be hardware failures, network problems (including some server being unavailable), or plain programming errors. These types of exceptional cases are often very hard to recover from. If a file is missing which we depend on, what could the program do about this? Nothing really. The program must notify the user but often that's all the program can do. If a failure depend on a programming error, it is probably best that the exception is logged (and sent to the developers somehow) and that the program exits gracefully. It could be argued that a buggy program is better off dying with the problem logged, than trying to keep running with a faulty state.

To give an example of when a program is better off dying because of a programming error, is when the program part which is saving critical data for the user can't save the data because of some programming error (the programmer forgot to initialize the variable holding the file name of the save-file, for instance). Rather than keeping running with the user thinking that her data is being saved in a safe place, the program should actually die with an error message (and the cause of the error logged for the developer so that they can fix the error!).

Chapters on the topic of Exceptions

Here are the chapters on the topic of Exceptions, so that you can check your progress:

Links

Source code

  • Code from presentations and solutions (github)

External links

Where to go next

The next page has exercises for this chapter: Exceptions - What is it - Exercises

« PreviousBook TOCNext »