Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exception Handling in Java

Similar presentations


Presentation on theme: "Exception Handling in Java"— Presentation transcript:

1 Exception Handling in Java
Mr Hanley, Shenendehowa High School 9/22/2014 Filled out 10/17/2016

2 What is exception handling?
A: Java taking exception to the code you type in A: All your code working except the important stuff A: Handling mail messages that go awry A: A robust mechanism for responding to run time errors

3 Throwing Exceptions Java has defined a class Exception, which allows control of the program to go to catch blocks of code that are designed to act as safeguards For example, when taking in a negative value a method can throw an exception to reject the negative value

4 Example public class Aircraft { private int altitude, fuel;
public void setAltitude(int alt) throws IllegalArgumentException { if (alt < 0 ) throw new IllegalArgumentException(“Out of range”); altitude = alt; //throw means quit the method look for a catch }

5 Flow A try catch block should be used by the caller of methods that throw Exceptions so they program can jump back to the catch block when thrown public class Client { public static void main(String[] args){ Aircraft a1 = new Aircraft(); //To do: finish with a try catch and assignment Scanner input = new Scanner(System.in); int newAlt = input.nextInt(); try { a1.setAltitude(newAlt); } catch(IllegalArgumentException iae) { //This is the handling block System.out.println(“Naughy, naughty”); }

6 Finally Block Use a finally block in order to clean up issues regardless of whether exceptions are thrown or not try { inVal = scan.nextDouble(); } catch (Exception e) { System.out.println(" Bad Character"); errorSnd.play(); } finally { scan.nextLine(); //This fixes the problem of the Scanner looping with same value

7 Checked and Unchecked Exceptions
Checked exceptions: Checked exceptions are checked at compile-time. It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error. It is named as checked exception because these exceptions are checked at Compile time. Opening a text file Unchecked exceptions: Unchecked exceptions are not checked at compile time. It means if your program is throwing an unchecked exception and even if you didn’t handle/declare that exception, the program won’t give a compilation error.  ArithmeticException Arithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsException Array index is out-of-bounds.

8 The End throw new EndOfPowerPointException (“I’m out”); The End


Download ppt "Exception Handling in Java"

Similar presentations


Ads by Google