Studyon Minte9.com
Head First (Java)




Exceptions



* Throws

	The compiler needs to know that you're calling a risky method. 
	You use "throws" in method declaration.

	%java

		package testingapp;
		public class TestingApp {
		    public static void main(String[] args) {
			doRisky("abc");
			    // Error: exception must be caugth or declared to be thrown
		    }
		    
		    static void doRisky(String test) throws Exception {
			
		    }
		}

* Try/Catch

	Ifyou wrap the risky code in something called a try/catch, the compiler is ok.

	%java
		
		package testingapp;
		public class TestingApp {
		    public static void main(String[] args) {
			
			try {
			    doRisky("yes");
			} catch (Exception e) {
			    System.out.println("Exception found!");
			}
			    // Output: Exception found!
		    }
		    
		    static void doRisky(String test) throws Exception {
			if ("yes".equals(test)) {
			    throw new Exception();
			}
		    }
		}


* Finally
	
	A finally block is where you put code that must run regardless of an exception.

	%java

		package testingapp;
		public class TestingApp {
		    public static void main(String[] args) {
			
			try {
			    doRisky("no"); 
				// no exception thrown
			    
			} catch (Exception e) {
			    System.out.println("Exception");
			} finally {
			    System.out.println("Finally");
			}
			    // Output: Finally
		    }
		    
		    static void doRisky(String test) throws Exception {
			if ("yes".equals(test)) {
			    throw new Exception();
			}
		    }
		}


* Multiple Exceptions

	A method can throw multiple exceptions.

	%java

		package testingapp;
		public class TestingApp {
		    public static void main(String[] args) {
			
			try {
			    
			    //doRisky(-10); // Output: Positive number required      
			    doRisky(10); // Output: My Error - Greater number required
			    
			} catch (Exception e) {
			    System.out.println(e.getMessage());
			} catch (myError me) {
			    System.out.println(me.getMessage());
			}
		    }
		    
		    static void doRisky(int n) throws Exception, myError {
			if (n < 0) {
			    throw new Exception("Positive number required");
			}
			
			if (Math.abs(n) < 20) {
			    throw new myError("Greater number required");
			}
		    }
		}

		class myError extends Error {
		    private String message;
		    public myError(String s) {
			message = s;
		    }
		    @Override
		    public String getMessage() {
			return "My Error - " + message;
		    }
		}



* Avoiding exception

	If you don't want to handle an exception, you can duck it by declaring it.

	%java

		package testingapp;
		public class TestingApp {
		    public static void main(String[] args) throws Exception {
			
			doRisky(-10);
				// No try/catch block 
				// The compiler is fine (because of "throws" in main method declaration)
		    }
		    
		    static void doRisky(int n) throws Exception {
			if (n < 0) {
			    throw new Exception("Positive number required");
			}
		    }
		}