90 likes | 104 Views
Learn about exceptions in Java, including creating, throwing, and catching exceptions. Practice by defining and throwing exceptions using conditional structures.
E N D
CS 112 - Fall 2012, Lab 07 Haohan Zhu
CS 112 - Fall 2012, Lab 07 Exception • Tutorial • http://docs.oracle.com/javase/tutorial/essential/exceptions/
CS 112 - Fall 2012, Lab 07 Exception • Class Throwable • http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html • Class Exception • http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html • Class Error • http://docs.oracle.com/javase/7/docs/api/java/lang/Error.html
CS 112 - Fall 2012, Lab 07 Exception • Definition: • An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
CS 112 - Fall 2012, Lab 07 Exception • Create an Exception • There exists many exceptions in Java • Throw an Exception • Throws clause needed for checked exceptions • Catch an Exception • Try-Catch-Finally Blocks
CS 112 - Fall 2012, Lab 07 Create an Exception • Extends Throwable or Exception • public class BadInputsException extends Throwable • { • public BadInputsException(String msg) • { • super(msg); • } • }
CS 112 - Fall 2012, Lab 07 Throw an Exception • Throws clause for checked exception (not Error or RuntimeException) • public class ThrowException { • public static void main(String[] args) throws BadInputsException{ • throw new BadInputsException("Hello World"); • } • }
CS 112 - Fall 2012, Lab 07 Catch an Exception • Try-Catch-Finally Blocks • try { • throw new BadInputsException("msg"); • } • catch (BadInputsException e) { • System.err.println("Catch a BadInputsException"); • } • finally { • System.out.println("Finished"); • }
CS 112 - Fall 2012, Lab 07 Practice • Define 2 exceptions • Throw exceptions by using a conditional structure (if - elseif - else)