meljun cortes java lecture exceptions
Post on 06-May-2015
248 Views
Preview:
DESCRIPTION
TRANSCRIPT
ExceptionsExceptions
Java Fundamentals and Object-Oriented Java Fundamentals and Object-Oriented ProgrammingProgramming
The Complete Java Boot CampThe Complete Java Boot Camp
MELJUN CORTESMELJUN CORTES
MELJUN CORTESMELJUN CORTES
TopicsTopics
What are Exceptions?What are Exceptions? IntroductionIntroduction The The ErrorError and and ExceptionException Classes Classes An ExampleAn Example
Catching ExceptionsCatching Exceptions The The trytry--catchcatch Statements Statements The The finallyfinally Keyword Keyword
TopicsTopics
Throwing ExceptionsThrowing Exceptions The The throwthrow Keyword Keyword The The throwsthrows Keyword Keyword
Exception CategoriesException Categories Exception Classes and HeirarchyException Classes and Heirarchy Checked and Unchecked ExceptionsChecked and Unchecked Exceptions User-Defined ExceptionsUser-Defined Exceptions
What are Exceptions?What are Exceptions?
Definition:Definition: Exceptional eventsExceptional events Errors that occur during runtimeErrors that occur during runtime Cause normal program flow to be disruptedCause normal program flow to be disrupted ExamplesExamples
Divide by zero errors Accessing the elements of an array beyond its
range Invalid input Hard disk crash Opening a non-existent file Heap memory exhausted
The Error and Exception The Error and Exception ClassesClasses ThrowableThrowable class class
Root class of exception classesRoot class of exception classes Immediate subclassesImmediate subclasses
Error Exception
Exception classException class Conditions that user programs can reasonably deal withConditions that user programs can reasonably deal with Usually the result of some flaws in the user program codeUsually the result of some flaws in the user program code ExamplesExamples
Division by zero error Array out-of-bounds error
The Error and Exception The Error and Exception ClassesClasses
Error classError class Used by the Java run-time system to handle Used by the Java run-time system to handle
errors occurring in the run-time environmenterrors occurring in the run-time environment Generally beyond the control of user programsGenerally beyond the control of user programs ExamplesExamples
Out of memory errors Hard disk crash
Exception ExampleException Example
11 class DivByZero {class DivByZero {22 public static void main(String args[]) public static void main(String args[]) {{
33 System.out.println(System.out.println(3/03/0););44 System.out.println(“Pls. print System.out.println(“Pls. print me.”);me.”);
55 }}66 }}
Exception ExampleException Example
Displays this error messageDisplays this error messageException in thread "main" Exception in thread "main" java.lang.ArithmeticException: / by zerojava.lang.ArithmeticException: / by zero
at DivByZero.main(DivByZero.java:3)at DivByZero.main(DivByZero.java:3)
Default handlerDefault handler Prints out exception descriptionPrints out exception description Prints the stack tracePrints the stack trace
Hierarchy of methods where the exception occurred Causes the program to terminateCauses the program to terminate
Catching Exceptions:Catching Exceptions:The The trytry--catchcatch Statements Statements
Syntax:Syntax:try {try { <code to be monitored for exceptions><code to be monitored for exceptions>} catch (<ExceptionType1> <ObjName>) {} catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs><handler if ExceptionType1 occurs>}}......} catch (<ExceptionTypeN> <ObjName>) {} catch (<ExceptionTypeN> <ObjName>) { <handler if ExceptionTypeN occurs><handler if ExceptionTypeN occurs>}}
Catching Exceptions:Catching Exceptions:The The trytry--catchcatch Statements Statements
11 class DivByZero {class DivByZero {22 public static void main(String args[]) {public static void main(String args[]) {33 try {try {44 System.out.println(3/0);System.out.println(3/0);55 System.out.println(“Please print System.out.println(“Please print
me.”);me.”);66 } catch (ArithmeticException exc) {} catch (ArithmeticException exc) {77 //Division by zero is an //Division by zero is an
ArithmeticExceptionArithmeticException88 System.out.println(exc);System.out.println(exc);99 }}1010 System.out.println(“After exception.”);System.out.println(“After exception.”);1111 }}1212 }}
Catching Exceptions:Catching Exceptions:The The trytry--catchcatch Statements Statements Multiple catch exampleMultiple catch example11 class MultipleCatch {class MultipleCatch {22 public static void main(String args[]) {public static void main(String args[]) {33 try {try {44 int den = Integer.parseInt(args[0]);int den = Integer.parseInt(args[0]);55 System.out.println(3/den);System.out.println(3/den);66 } catch (ArithmeticException exc) {} catch (ArithmeticException exc) {77 System.out.println(“Divisor was 0.”);System.out.println(“Divisor was 0.”);88 } catch (ArrayIndexOutOfBoundsException exc2) {} catch (ArrayIndexOutOfBoundsException exc2) {99 System.out.println(“Missing argument.”);System.out.println(“Missing argument.”);1010 }}1111 System.out.println(“After exception.”);System.out.println(“After exception.”);1212 }}1313 }}
Catching Exceptions:Catching Exceptions:The The trytry--catchcatch Statements Statements
Nested Nested trytryss11 class NestedTryDemo {class NestedTryDemo {22 public static void main(String args[]){public static void main(String args[]){33 try {try {44 int a = Integer.parseInt(args[0]);int a = Integer.parseInt(args[0]);55 try {try {66 int b = Integer.parseInt(args[1]);int b = Integer.parseInt(args[1]);77 System.out.println(a/b);System.out.println(a/b);88 } catch (ArithmeticException e) {} catch (ArithmeticException e) {99 System.out.println(“Div by zero System.out.println(“Div by zero error!");error!");
1010 }}1111 //continued...//continued...
Catching Exceptions:Catching Exceptions:The The trytry--catchcatch Statements Statements
1111 } catch } catch (ArrayIndexOutOfBoundsException) {(ArrayIndexOutOfBoundsException) {
1212 System.out.println(“Need 2 System.out.println(“Need 2 parameters!");parameters!");
1313 }}1414 }}1515 }}
Catching Exceptions:Catching Exceptions:The The trytry--catchcatch Statements Statements
Nested Nested trytrys with methodss with methods1.1. class NestedTryDemo2 {class NestedTryDemo2 {2.2. static void nestedTry(String args[]) {static void nestedTry(String args[]) {3.3. try {try {4.4. int a = Integer.parseInt(args[0]);int a = Integer.parseInt(args[0]);5.5. int b = Integer.parseInt(args[1]);int b = Integer.parseInt(args[1]);6.6. System.out.println(a/b);System.out.println(a/b);7.7. } catch (ArithmeticException e) {} catch (ArithmeticException e) {8.8. System.out.println("Div by zero System.out.println("Div by zero error!");error!");
9.9. }}10.10. }}11.11.//continued...//continued...
Catching Exceptions:Catching Exceptions:The The trytry--catchcatch Statements Statements
12.12. public static void main(String public static void main(String args[]){args[]){
13.13. try {try {14.14. nestedTry(args);nestedTry(args);15.15. } catch } catch (ArrayIndexOutOfBoundsException e) {(ArrayIndexOutOfBoundsException e) {
16.16. System.out.println("Need 2 System.out.println("Need 2 parameters!");parameters!");
17.17. }}18.18. }}19.19.}}
Catching Exceptions:Catching Exceptions:The The finallyfinally Keyword Keyword
Syntax:Syntax:try {try { <code to be monitored for exceptions><code to be monitored for exceptions>} catch (<ExceptionType1> <ObjName>) {} catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs><handler if ExceptionType1 occurs>} ...} ...} finally {} finally { <code to be executed before the try block <code to be executed before the try block ends>ends>
}}
Contains the code for cleaning up after a try or a Contains the code for cleaning up after a try or a catchcatch
Catching Exceptions:Catching Exceptions:The The finallyfinally Keyword Keyword
Block of code is always executed despite of Block of code is always executed despite of different scenarios:different scenarios: Forced exit occurs using a Forced exit occurs using a returnreturn, a , a continuecontinue or or
a a breakbreak statement statement Normal completionNormal completion Caught exception thrownCaught exception thrown
Exception was thrown and caught in the method Uncaught exception thrownUncaught exception thrown
Exception thrown was not specified in any catch block in the method
Catching Exceptions:Catching Exceptions:The The finallyfinally Keyword Keyword11 class FinallyDemo {class FinallyDemo {22 static void myMethod(int n) throws Exception{static void myMethod(int n) throws Exception{33 try {try {44 switch(n) {switch(n) {55 case 1: System.out.println("1st case");case 1: System.out.println("1st case");66 return;return;77 case 3: System.out.println("3rd case");case 3: System.out.println("3rd case");88 throw new throw new
RuntimeException("3!");RuntimeException("3!");99 case 4: System.out.println("4th case");case 4: System.out.println("4th case");1010 throw new Exception("4!");throw new Exception("4!");1111 case 2: System.out.println("2nd case");case 2: System.out.println("2nd case");1212 }}1313 //continued...//continued...
Catching Exceptions:Catching Exceptions:The The finallyfinally Keyword Keyword
1414 } catch (RuntimeException e) {} catch (RuntimeException e) {1515 System.out.print("RuntimeException: ");System.out.print("RuntimeException: ");
1616 System.out.println(e.getMessage());System.out.println(e.getMessage());
1717 } finally {} finally {1818 System.out.println("try-block System.out.println("try-block entered.");entered.");
1919 }}2020 }}2121 //continued...//continued...
Catching Exceptions:Catching Exceptions:The The finallyfinally Keyword Keyword
2222 public static void main(String args[]){public static void main(String args[]){2323 for (int i=1; i<=4; i++) {for (int i=1; i<=4; i++) {2424 try {try {2525 FinallyDemo.myMethod(i);FinallyDemo.myMethod(i);2626 } catch (Exception e){} catch (Exception e){2727 System.out.print("Exception caught: System.out.print("Exception caught:
");");2828 System.out.println(e.getMessage());System.out.println(e.getMessage());2929 }}3030 System.out.println();System.out.println();3131 }}3232 }}3333 }}
Throwing Exceptions: Throwing Exceptions: The The throwthrow Keyword Keyword
Java allows you to throw exceptions:Java allows you to throw exceptions:throw <exception object>;throw <exception object>;
Example:Example:throw new throw new ArithmeticException(“testing...”);ArithmeticException(“testing...”);
Throwing Exceptions: Throwing Exceptions: The The throwthrow Keyword Keyword
11 class ThrowDemo {class ThrowDemo {22 public static void main(String args[]){public static void main(String args[]){33 String input = “invalid input”;String input = “invalid input”;44 try {try {55 if (input.equals(“invalid input”)) {if (input.equals(“invalid input”)) {66 throw new RuntimeException("throw demo");throw new RuntimeException("throw demo");77 } else {} else {88 System.out.println(input);System.out.println(input);99 }}1010 System.out.println("After throwing");System.out.println("After throwing");1111 } catch (RuntimeException e) {} catch (RuntimeException e) {1212 System.out.println("Exception caught:" + e);System.out.println("Exception caught:" + e);1313 }}1414 }}1515 }}
Throwing Exceptions: Throwing Exceptions: The The throwsthrows Keyword Keyword
A method is required to either catch or list all exceptions it A method is required to either catch or list all exceptions it might throwmight throw Except for Except for ErrorError or or RuntimeExceptionRuntimeException, or their subclasses, or their subclasses
If a method may cause an exception to occur but does not If a method may cause an exception to occur but does not catch it, then it must say so using the catch it, then it must say so using the throwsthrows keyword keyword Applies to checked exceptions onlyApplies to checked exceptions only
Syntax:Syntax:<type> <methodName> (<parameterList>) <type> <methodName> (<parameterList>) throws throws <exceptionList><exceptionList> { {
<methodBody><methodBody>}}
Throwing Exceptions: Throwing Exceptions: The The throwsthrows Keyword Keyword
11 class ThrowingClass {class ThrowingClass {22 static void meth() static void meth() throws ClassNotFoundExceptionthrows ClassNotFoundException { {33 throw new ClassNotFoundException ("demo");throw new ClassNotFoundException ("demo");44 }}55 }}66 class ThrowsDemo {class ThrowsDemo {77 public static void main(String args[]) {public static void main(String args[]) {88 try {try {99 ThrowingClass.meth();ThrowingClass.meth();1010 } catch (ClassNotFoundException e) {} catch (ClassNotFoundException e) {1111 System.out.println(e);System.out.println(e);1212 }}1313 }}1414 }}
Exception Classes and Exception Classes and HierarchyHierarchy
Exception Classes and Exception Classes and HierarchyHierarchy
Multiple catches should be ordered from subclass to Multiple catches should be ordered from subclass to superclass.superclass.
11 class MultipleCatchError {class MultipleCatchError {22 public static void main(String args[]){public static void main(String args[]){33 try {try {44 int a = Integer.parseInt(args [0]);int a = Integer.parseInt(args [0]);55 int b = Integer.parseInt(args [1]);int b = Integer.parseInt(args [1]);66 System.out.println(a/b);System.out.println(a/b);77 } catch (Exception ex) {} catch (Exception ex) {88 } catch (ArrayIndexOutOfBoundsException e) {} catch (ArrayIndexOutOfBoundsException e) {99 }}1010 }}1111 }}
Checked and Unchecked Checked and Unchecked ExceptionsExceptions
Checked exceptionChecked exception Java compiler checks if the program either catches or lists the Java compiler checks if the program either catches or lists the
occurring checked exceptionoccurring checked exception If not, compiler error will occurIf not, compiler error will occur
Unchecked exceptionsUnchecked exceptions Not subject to compile-time checking for exception handlingNot subject to compile-time checking for exception handling Built-in unchecked exception classesBuilt-in unchecked exception classes
Error RuntimeException Their subclasses
Handling all these exceptions may make the program cluttered Handling all these exceptions may make the program cluttered and may become a nuisanceand may become a nuisance
User-Defined ExceptionsUser-Defined Exceptions
Creating your own exceptionsCreating your own exceptions Create a class that Create a class that extendsextends the the RuntimeExceptionRuntimeException or the or the
ExceptionException class class Customize the class Customize the class
Members and constructors may be added to the class
Example:Example:11 class HateStringExp class HateStringExp extends extends RuntimeException RuntimeException {{
22 /* No longer add any member or /* No longer add any member or constructor */constructor */
33 }}
User-Defined ExceptionsUser-Defined Exceptions
Using user-defined exceptionsUsing user-defined exceptions11 class TestHateString {class TestHateString {22 public static void main(String args[]) {public static void main(String args[]) {33 String input = "invalid input";String input = "invalid input";44 try {try {55 if (input.equals("invalid input")) {if (input.equals("invalid input")) {66 throw new HateStringExp();throw new HateStringExp();77 }}88 System.out.println("Accept string.");System.out.println("Accept string.");99 } catch (} catch (HateStringExp eHateStringExp e) {) {1010 System.out.println("Hate string!”);System.out.println("Hate string!”);1111 }}1212 }}1313 }}
SummarySummary
DefinitionDefinition trytry, , catchcatch and and finallyfinally throwthrow and and throwsthrows ThrowableThrowable, , ExceptionException, , ErrorError classes classes Checked and Unchecked ExceptionsChecked and Unchecked Exceptions User-Defined ExceptionsUser-Defined Exceptions
top related