Java Puzzle 29 – Catch Exception
Merhaba Arkadaslar
Bu bir kac try-catch ornegi inceleyecegiz.
Hemen ilk ornegimize bakalim ;
CatchIOException.java
package _29.catch$; import java.io.IOException; public class CatchIOException { public static void main(String[] args) { try { System.out.println("Hello CatchIOException#main !"); } catch (IOException e) { System.out.println("I have never seen println fail!"); } } }
Ornek kodumuzu inceleyelim , basitce Hello CatchIOException#main yazacak gibi durmakta fakat derleme hatasi/compile error verecektir.
Bunun nedeni , try blogu hic bir zaman IOException firlatamaz bu nedenle derleme hatasi vermektedir. IOException bir checked exception’dir.
Unreachable catch block for IOException. This exception is never thrown from the try statement body
Bir baska ornek olarak ;
CatchException.java
package _29.catch$; public class CatchException { public static void main(String[] args) { try { System.out.println("Hello CatchException#main!"); } catch (Exception e) { System.out.println("I have never seen println fail!"); } } }
java.lang.Exception da bir Checked Exception olmasina ragmen bu kod calisir derleme hatasi vermez !
Bu istina durum java.lang.Exception ve java.lang.Throwable icin gecerlidir. Bunlarin disindaki Checked Exception’lar icin eger ilgili exception’inin firlatilma riski yoksa catch blogunda yazmak derleme hatasi/compile hatasi verecektir.
Unchecked Exceptionlar icin de ornegimiz calisacaktir.
CatchRuntimeException.java
package _29.catch$; public class CatchRuntimeException { public static void main(String[] args) { try { System.out.println("Hello CatchRuntimeException#main!"); } catch (RuntimeException e) { System.out.println("I have never seen println fail!"); } } }
Github kaynak kodlar / Source Code ;
leventerguder/injavawetrust-puzzler
Yazimi burada sonlandiriyorum.
Herkese Bol Javali Gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
OCP, Java SE 6 Programmer
OCE, Java EE 6 Web Component Developer
Leave a Reply