1. Study materials

Slides:

2. Additional pointers

3. Exercises

Think test driven! So write tests FIRST, and then code. Testing is ensuring that the code is usable. To make code testable is also a design exercise: you need to make decisions about the design of your program when you write your tests. If you cannot test it, you cannot use it.

3.1. Something Broken in the Land of Exceptions

3.1.1. Read The Fine Compiler Messages

What is the effect of the code below? It may be wrong.

  1. Explain what will happen.

  2. Feed it to the compiler, e.g. by using NetBeans-IDE and see what the compiler thinks of it. Explain any messages you may get.

This is an exercise in RTFCM (Read The Fine Compiler Messages).

Do not repair the code if it appears broken.
something with Exceptions
class X {
  void m(){
    Object e = new RuntimeException("lets rock the world");
    throw e;
  }
}

3.1.2. More Broken Exceptions

What is the effect of the code below? It may be wrong.

  1. Explain what happens what will happen.

  2. Feed it to the compiler, e.g. by using NetBeans and see what the compiler thinks of it. Explain any messages you may get.

This is an exercise in RTFCM (Read The Fine Compiler Messages).

Do not repair the code if it appears broken.
something with Exceptions
class Y {
  void m(){
    Exception e = new Exception("got you this time");
    try {
      throw e;
    } catch( e ) {
      System.out.println(e.getMessage());
      throw e;
    }
  }
}

3.2. In the pub.

Do the exercise described in the document below. Note that you not only have to throw exceptions, but must also TEST that they are thrown for the right reasons.

Here is how you could start the BarkeeperTest class. First you create a barkeeper that you use in your tests.

    private Barkeeper barkeeper;

    @Before
    public void setUp() {
        barkeeper = new Barkeeper();
    }

In your first test method, you want to test whether the tapping of beer works as intended. Let the test fail first, then implement the logic of that test. When you have finished, continue to the next part: for example, when there is no beer left, the tapBeer() Method should throw an EmptyStockException.

    @Test
    public void test_tapBeer_ok() {
        try {
            assertSame( "Should get a beer with pint volume", DrinkVolume.PINT,
                    barkeeper.tapBeer( new Stock( 20 ), new Guest( 56, 2, false ),
                            DrinkVolume.PINT ).getVolume() );

        } catch ( TooYoungException | BobException | EmptyStockException ex ) {
            fail( "here should be no exception" );
        }
    }

Here is the link to the entire exercise:

3.3. Shopping Cart

The shopping cart exercise is about working with interfaces and exceptions.

Task description Shopping cart.

Netbeans starter project will be available in your repo.


4. YouTube Lesson 2

These are the recordings of the PRC2 lesson on 2019-02-14, 2nd part.

Exceptions and how you can catch them