Learning Java: Day 11

Exception Handling
Anytime you work with computers, stuff happens. The server is down. The network is offline. The file is corrupted.  As a programmer you need to write code that can handle the bad times; problem-handling code for when you can't guarantee that the file will be in the right directory, the server will be up and running, or the Thread stays asleep. Chapter 11 of Head First Java covers this kind of problem anticipation.

We will be building a MIDI Music Player.  Over the next three chapters we'll learn to create a graphical user interface (GUI) and a multi-user BeatBox Drum Machine. Today we learn what is required to create a MIDI player and how to handle exceptions.

Risky Business
When your code calls a risky method -- a method that declares an exception -- it's the risky method that throws the exception back to you, the caller. You have to read the API docs to see if there is risky behavior in the code.  The method has to declare the exceptions it might throw. The API docs then tell you WHEN you might get that exception, such as resource restrictions because the object (in this case, the sequencer) might already be in use. It's up to you to write code to deal with the problem.

Checked Exception vs RuntimeException
RuntimeExceptions occur because you've got flaws in your code that need to be fixed before the code will compile.
Checked Exceptions happen while the program is running and are caused when a method throws an exception with the keyword throw,  followed by a new exception object:
     throw new noJuiceFastException();
Methods that might throw a checked exception must announce it with a throws Exception declaration. Methods can throw more than one exception.

Try/Catch
A try/catch block tells the compiler that you know an exceptional thing could happen in the method you're calling, and that you're prepared to handle it. The compiler doesn't care how you handle it; it cares only that you say you're taking care of it.

  • Exceptions are polymorphic
  • Write a different catch block for each exception that you need to handle uniquely.
  • Multiple catch blocks must be ordered from smallest to biggest.
Making Sounds
You need four things:
  1. Sequencer: The thing that plays the music
  2. Sequence: The music to be played...a song
  3. Track: The part of the Sequence that holds the actual information
  4. Midi Event: The actual music information (notes to play, how long, etc.)
Today we use command line arguments to experiment with sounds. Next chapter we create MIDI events using a very crude video that pulses to the beat of the MIDI music. 

Onward...

0 comments:

Post a Comment