11. 예외처리 학습목표 음악재생프로그램예외처리방법 try/catch 블록예외선언방법
위험한행동 예상치못한상황 파일이없는경우 서버가다운되는경우 장치를사용할수없는경우 이런예외적인상황을처리하기위한방법이필요합니다. 자바의예외처리메커니즘 try/catch 블록 예외선언
음악재생프로그램
JavaSound API JavaSound API MIDI 악기디지털인터페이스 (Musical Instruments Digital Interface) Sampled
Sequencer import javax.sound.midi.*; public class MusicTest1 { public void play() { Sequencer sequencer = MidiSystem.getSequencer(); System.out.println( We got a sequencer ); public static void main(string[] args) { MusicTest1 mt = new MusicTest1(); mt.play(); % javac MusicTest1.java MusicTest1.java:5: unreported exception javax.sound.midi.midiunavailableexception; must be caught or declared to be thrown Sequencer sequencer = MidiSystem.getSequencer(); ^ 1 error
위험요소가있는메소드 프로그래머프로그래머가만든코드코드에서사용하는메소드가들어있는클래스
예외처리메커니즘 예외 (exception) 프로그램실행중에생길수있는특이한상황 예외처리 (exception handling) 메커니즘 오류처리코드를한군데로모아놓을수있기때문에코드가깔끔해지고효율적이됩니다.
try/catch 블록 예외를처리할것임을알려주기위한용도로쓰임 import javax.sound.midi.*; public class MusicTest1 { public void play() { try { Sequencer sequencer = Midisystem.getSequencer(); System.out.println( Successfully got a sequencer ); catch (MidiUnavailableException ex) { System.out.println( Bummer ); public static void main(string[] args) { MusicTest1 mt = new MusicTest1(); mt.play();
Exception 클래스 try { // 위험한일처리 catch (Exception ex) { // 문제해결 Throwable getmessage() printstacktrace() Exception IOException InterruptedException
예외던지기와잡기 예외를던지는코드 public void takerisk() throws BadException { if (abandonallhope) { throw new BadException(); 위험한메소드를호출하는코드 public void crossfingers() { try { anobject.takerisk(); catch (BadException ex) { System.out.println( Aaargh! ); ex.printstacktrace();
확인예외 확인예외 (checked exception) RuntimeException 을제외한모든예외 코드에서예외를던진다면반드시메소드를선언하는부분에서 throws 키워드를써야함 예외를던지는메소드를호출하면 try/catch 블록으로그부분을감싸거나그메소드에서도예외를선언해야함
바보같은질문은없습니다. NullPointerException, DivideByZero 같은예외에대해서는왜 try/catch 블록을사용하지않나요? RuntimeException 및그하위클래스에속하는예외는컴파일러에서잡아내지않습니다. 런타임예외는실행중에어떤조건에문제가생기는경우보다는코드의논리에예측 / 예방할수없는방식으로문제가생기는경우에발생합니다. try/catch 블록은예외적인상황을처리하기위한것이지코드의문제점을보완하기위한것은아닙니다.
try/catch 블록의흐름제어 try { Foo f = x.doriskything(); int b = f.getnum(); catch (Exception ex) { System.out.println( failed ); System.out.println( We made it! ); % java Tester We made it! % java Tester failed We made it!
무조건실행할내용 예외발생여부와상관없이무조건실행할코드는 finally 블록에... try { turnovenon(); x.bake(); catch (BakingException ex) { ex.printstacktrace(); finally { turnovenoff(); try { turnovenon(); x.bake(); turnovenoff(); catch (BakingException ex) { ex.printstacktrace(); turnovenoff();
두개이상의예외 예외를여러개던진다면모든확인예외를잡아야합니다. public class Laundry { public void dolaundry() throws PantsException, LingerieException { // 두가지예외를던질수있는코드 public class Foo { public void go() { Laundry laundry = new Laundry(); try { laundry.dolaundry(); catch (PantsException pex) { catch (LingerieException lex) {
예외와다형성 public void dolaundry throws ClothingException { Exception ClothingException catch (ClothingException cex) { PantsException LingerieException ShirtException catch (ShirtException sex) { TeeShirtException DressShirtException
작은것부터큰것으로 try { laundry.dolaundry(); catch(teeshirtexception tex) { catch(lingerieexception lex) { catch(clothingexception cex) {
예외선언 try/catch 블록을쓰는대신메소드에서예외를선언함으로써예외처리를회피하는방법도있습니다. public void foo() throws ReallyBadException { // try/catch 블록없이위험한메소드호출 laundry.dolaundry();
예외선언 public class Washer { Laundry laundry = new Laundry(); public void foo() throws ClothingException { laundry.dolaundry(); public static void main(string[] args) throws ClothingException { Washer a = new Washer(); a.foo(); dolaundry() foo() main() foo() main() main()
다시음악코드로 import javax.sound.midi.*; public class MusicTest1 { public void play() { try { Sequencer sequencer = MidiSystem.getSequencer(); System.out.println( Successfully got a sequencer ); catch(midiunavailableexception ex) { System.out.println( Bummer ); public static void main(string[] args) { MusicTest1 mt = new MusicTest1(); mt.play();
예외와관련된규칙 1. try 없이 catch 나 finally 만쓸수는없음 void go() { Foo f = new Foo(); f.foof(); catch(fooexception ex) { 2. try 와 catch 사이에코드를집어넣을수없음 try { x.dostuff(); int y = 43; catch(exception ex) {
예외와관련된규칙 3. try 뒤에는반드시 catch 나 finally 가있어야함 try { x.dostuff(); finally { 4. try 뒤에 finally 만있으면예외선언 void go() throws FooException { try { x.dostuff(); finally {
JavaSound API 음악을재생하는장치 Sequencer 재생할음악 Sequence 실제정보가들어있는부분 Track 실제음악정보 MidiEvent
JavaSound API 1. 시퀀서만들고열기 Sequencer player = MidiSystem.getSequencer(); 2. 새로운시퀀스만들기 Sequence seq = new Sequence(timing, 4); 3. 시퀀스에서새로운트랙가져오기 Track t = seq.createtrack(); 4. 트랙에 MidiEvent 를채우고시퀀스를시퀀서에넘기기 t.add(mymidievent1); player.setsequence(seq); 5. 시퀀서에대해 play() 메소드호출 player.start();
MidiEvent 1. Message 만들기 ShortMessage a = new ShortMessage(); 2. 메시지에지시사항넣기 a.setmessage(144, 1, 44, 100); 메시지유형 음높이 3. 새로운 MidiEvent 만들기 MidiEvent noteon = new MidiEvent(a, 1); 채널 속도 4. MidiEvent 를트랙에추가 track.add(noteon);
숙제 본문을꼼꼼하게읽어봅시다. 연필을깎으며및 11 장끝에있는연습문제를모두각자의힘으로해결해봅시다. API 문서에서이장에나와있는클래스및메소드에대한내용을직접찾아봅시다.