Advanced Programming in Java Peyman Dodangeh Sharif University
- Slides: 55
Advanced Programming in Java Peyman Dodangeh Sharif University of Technology Fall 2013
Agenda �Error handling mechanisms �Exception handling framework �Benefits of exception handling framework �Exception handling in Java Sharif University of Technology 2
Watch This Method public static Integer get. Year(String day){ String year. String = day. substring(0, 4); int year = Integer. parse. Int(year. String); return year; } public static void main(String[] args) { String day = "2013/11/30"; Integer year = get. Year(day); System. out. println(year); } Sharif University of Technology 3
Exceptions �What is wrong with it? �What if day parameter is not a day representation? �day = “salam!” �What if day parameter is malformed? �Day = “ 30 Nov 2013” �What if day parameter is empty? �String s = ""; �What if day parameter is null? �These occasions are called Exception Sharif University of Technology 4
Handling Exceptions �What to do with exceptions? �Exit the program �Printing the error on console �Returning a special value �e. g. -1 Sharif University of Technology 5
Important Note �Sometimes the method can’t handle the exception effectively �What should a method do when an exception occurs? �Exit the program? �Suppose you are in a desktop application � Excel, Word, a game, … �Print on console? �edu site �A game Sharif University of Technology 6
Returning a Special Value �We can return a special value to report an exception �E. g. �return null; �return -1; �return 0; �return “”; �Why not? Sharif University of Technology 7
Why not? �There is no special value �There are many exceptions �Ambiguity �Need for documentation �Combination of program code and exception code Sharif University of Technology 8
There is no special value public static int minimum(int[] nums ){ int m = Integer. MAX_VALUE; for (int i : nums) { m = Math. min(m, i); } return m; } int[] array = {1, 2, -1}; int minimum. Found = minimum(array); Sharif University of Technology 9
Exception Handling �Exception Handling is a framework for handling exceptions �; -) �It simplifies code �Separates business code and exception code Sharif University of Technology 10
What is an Exception? �Exceptional event �Error that occurs during runtime �Cause normal program flow to be disrupted �Examples �? �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 Sharif University of Technology 11
Default Exception Handling �Provided by Java runtime �Prints out exception description �Prints the stack trace �Hierarchy of methods where the exception occurred �Causes the program to terminate Sharif University of Technology 12
Example 17 class Div. By. Zero { 18 public static void main(String a[]) { 19 System. out. println(3/0); 20 } 21 } Exception in thread "main" java. lang. Arithmetic. Exception: / by zero at exception. Test 2. main(Test 2. java: 19) �Note: Exception is a runtime concept �This code has no syntax error (No compile-time error) Sharif University of Technology 13
What Happens When an Exception Occurs? �When an exception occurs within a method �The method creates an exception object �And hands it off to the runtime system �This job is called “throwing an exception” �Exception object contains �information about the error �its type �the state of the program when the error occurred � Exception line of code Sharif University of Technology 14
What Happens When an Exception Occurs (2)? �The runtime system searches the call stack for a method that contains an exception handler �When an appropriate handler is found �The runtime system passes the exception to the handler �The exception handler catches the exception �What if the runtime system can not find an exception handler? �Uses the default exception handler Sharif University of Technology 15
` Sharif University of Technology 16
Sharif University of Technology 17
Exception Handling in Java public static Integer get. Year(String day) { String year. String = day. substring(0, 4); int year = Integer. parse. Int(year. String); return year; } public static void main(String[] args) { Scanner scanner = new Scanner(System. in); System. out. print("Enter a well-formed date: "); String date = scanner. next(); Integer year = get. Year(date); System. out. println(year); } Sharif University of Technology 18
get. Year() public static Integer get. Year(String day) throws Exception { if (day == null) throw new Exception("null value"); if (day. length() == 0) throw new Exception("empty value"); if (!matches. Date. Format(day)) throw new Exception("malformed value"); String year. String = day. substring(0, 4); int year = Integer. parse. Int(year. String); return year; } private static boolean matches. Date. Format(String input) { return input. matches("\d\d/\d\d"); } Sharif University of Technology 19
main() public static void main(String[] args) { Scanner scanner = new Scanner(System. in); boolean ok = false; while (ok == false) { System. out. print("Enter a well-formed date: "); String date = scanner. next(); try { Integer year = get. Year(date); System. out. println(year); ok = true; } catch (Exception e) { System. out. println(e. get. Message()); } } } Sharif University of Technology 20
Exception Handling Keywords �throws a new exception �throws �Declares exception throw �If a method may throw an exception, it should declare it �try �Start a block with exception handling �catch �Catch the exception Sharif University of Technology 21
Benefits of Exception Handling Framework �Separating Error-Handling code from “regular” business logic code �Propagating errors up the call stack �Grouping and differentiating error types Sharif University of Technology 22
Example Sharif University of Technology 23
Separating Error-Handling Code �Consider pseudocode method �It reads an entire file into memory read. File { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } Sharif University of Technology 24
Traditional Programming Sharif University of Technology 25
With Exception Handling Framework Sharif University of Technology 26
Note �You should still write code for detecting, reporting and handling exceptions �Exception handling framework is not responsible for these jobs! �It only helps you organize the work more effectively Sharif University of Technology 27
Propagating Errors Up the Call Stack �Traditional approach �Each method should explicitly forward the exception �Use a special return code �Using return type for reporting exceptions � Smells bad! �New approach �Automatic �Beautiful! Sharif University of Technology 28
Sharif University of Technology 29
Grouping and Differentiating Error Types �All exceptions thrown within a program are objects �The grouping or categorizing of exceptions is a natural outcome of the class hierarchy Sharif University of Technology 30
Sharif University of Technology 31
Example class Multiple. Catch { public static void main(String args[]) { try { int den = Integer. parse. Int(args[0]); System. out. println(3/den); } catch (Arithmetic. Exception exc) { System. out. println(“Divisor was 0. ”); } catch (Array. Index. Out. Of. Bounds. Exception exc 2) { System. out. println(“Missing argument. ”); } System. out. println(“After exception. ”); } } Sharif University of Technology 32
Nested Tries class Nested. Try. Demo { public static void main(String args[]){ try { int a = Integer. parse. Int(args[0]); try { int b = Integer. parse. Int(args[1]); System. out. println(a/b); } catch (Arithmetic. Exception e) { System. out. println(“Div by zero error!"); } } catch (Array. Index. Out. Of. Bounds. Exception) { System. out. println(“Need 2 parameters!"); } } } Sharif University of Technology 33
Bad Use of Exceptions �Don’t Use Exception instead of If-else �Use exceptions for exceptions! Sharif University of Technology 34
Writing Your Own Exceptions �Your class should extend Exception class �Exception subclasses could be thrown and caught �Steps to follow �Create a class that extends Exception class �Customize the class � Members and constructors may be added to the class �Exception classes are usually simple classes �With no (or few) methods and properties Sharif University of Technology 35
Example class Hate. String. Exp extends Exception { /* some code */ } String input = "invalid input"; try { if (input. equals("invalid input")) { throw new Hate. String. Exp(); } System. out. println("Accept string. "); } catch (Hate. String. Exp e) { System. out. println("Hate string!”); } Sharif University of Technology 36
get. Year(), revisited public static Integer get. Year(String day) throws Exception { if (day == null) throw new Null. Pointer. Exception(); if (day. length() == 0) throw new Empty. Value. Exception(); if (!matches. Date. Format(day)) throw new Malformed. Value. Exception(); String year. String = day. substring(0, 4); int year = Integer. parse. Int(year. String); return year; } private static boolean matches. Date. Format(String input) { return input. matches("\d\d/\d\d"); } Sharif University of Technology 37
Finally try { //. . } catch (Exception. Type e) { //… }. . . } finally { <code to be executed before the try block ends> } �Contains the code for cleaning up after a try or a catch Sharif University of Technology 38
Finally (2) �Block of code is always executed �Despite of different scenarios: �Normal completion �Forced exit occurs using a return, a continue or a break statement �Caught exception thrown �Exception was thrown and caught in the method �Uncaught exception thrown �Exception thrown was not specified in any catch block in the method Sharif University of Technology 39
Sharif University of Technology 40
public static int my. Method(int n) { try { switch (n) { class My. Exception extends Exception {} case 1: System. out. println("One"); return 1; case 2: System. out. println("Two"); throw. My. Exception(); case 3: System. out. println("Three"); } private static void throw. My. Exception() return 4; throws My. Exception { } catch (Exception e) { throw new My. Exception(); System. out. println("catch"); } return 5; } finally { System. out. println("finally"); int a = my. Method(1); return 6; System. out. println("my. Method(1)=" + a); } a = my. Method(2); System. out. println("my. Method(2)=" + a); a = my. Method(3); Sharif University of Technology System. out. println("my. Method(3)=" + a); Quiz! 41
Result: �One �finally �my. Method(1)=6 �Two �catch �finally �my. Method(2)=6 �Three �finally �my. Method(3)=6 Sharif University of Technology 42
Unchecked Exceptions private static void function(String[] args) { int den = Integer. parse. Int(args[0]); System. out. println(3 / den); } public static void main(String[] args) { function(args); } �The method function() may throw exceptions �But it has not declared it with throws keyword �Why? � Because some exceptions are unchecked � such as Arithmetic. Exception and Array. Index. Out. Of. Bounds. Exception Sharif University of Technology 43
Checked and Unchecked Exceptions �Checked exception �Java compiler checks �the program should catch or list the occurring exception �If not, compiler error will occur �Unchecked exceptions �Not subject to compile-time checking for exception handling �Built-in unchecked exception classes �Error �Runtime. Exception �Their subclasses �Unchecked exceptions only relax compiler �The runtime behavior is the same Sharif University of Technology 44
Exception Class Hierarchy Sharif University of Technology 45
Exception Classes and Hierarchy �Multiple catches should be ordered from subclass to superclass �Or else, Compile error: Unreachable catch block… class Multiple. Catch. Error { public static void main(String args[]){ try { int a = Integer. parse. Int(args [0]); int b = Integer. parse. Int(args [1]); System. out. println(a/b); } catch (Array. Index. Out. Of. Bounds. Exception e) { //. . } catch (Exception ex) { //. . } } } Sharif University of Technology 46
Exceptions & Inheritance �Suppose method f() overrides parent’s method �f() in child class can not throw more exceptions than those of f() in Parent class �Less or equal exceptions in throws declaration �These mistakes bring compiler error �Why? �Polymorphic method invocations may cause failure in catching some exceptions Sharif University of Technology 47
Example (1) class void } Parent{ f(){} Child extends Parent{ f()throws Exception{} �Result? �Compiler Error Sharif University of Technology 48
Example (2) class Parent{ void f()throws Arithmetic. Exception{} } class Child extends Parent{ void f()throws Arithmetic. Exception, IOException{} } �Result? �Compiler Error Sharif University of Technology 49
Example (3) class Parent{ void f()throws Arithmetic. Exception{} } class Child extends Parent{ void f()throws Exception{} } �Result? �Compiler Error Sharif University of Technology 50
Example (4) class void } Parent{ f()throws Exception{} Child extends Parent{ f()throws Arithmetic. Exception{} �Result? �No Error Sharif University of Technology 51
Conclusion �f() in child class can not throw more exceptions �Less or equal exceptions in throws declaration �f() in child class can not throw more general exceptions �f() in child class can throw more specific exceptions �Reason: �Prevent uncaught exceptions in polymorphic invocations Sharif University of Technology 52
Further Reading �Throwable and Error classes Sharif University of Technology 53
References http: //docs. oracle. com/javase/tutorial/essential/exceptions /index. html Sharif University of Technology 54
Sharif University of Technology 55
- Advanced programming in java
- دکتر علیرضا پیمان
- Peyman milanfar
- دکتر پیمان چشم پزشک اصفهان
- Peyman kazemian
- Peyman haghighat
- Alireza yalda
- Sharif university of technology
- Muhammad nawaz sharif university of agriculture
- Advanced dynamic programming
- Advanced internet programming
- Forward reference table (frt) is arranged like ?
- Imperative statement in assembly language
- Advanced data structures in java
- Object oriented programming java exercises
- Perbedaan linear programming dan integer programming
- Greedy vs dynamic programming
- What is system program
- Integer programming vs linear programming
- Definisi integer
- Sharif kite runner
- Mail.ce.sharif
- Leila sharif
- Faisal mosque
- Edu.sharif.edu
- Mohammad vesal
- Kesan penentangan sharif masahor
- Peristiwa penentangan sharif masahor
- Cw.sharif.eud
- Sharif
- Sebab penentangan rentap di sarawak
- Bg
- Behjat sharif
- Lentiform nucleus
- Ayan sharif
- Shamshuritawati sharif
- Pico and finer criteria
- Application
- Java parallel programming
- Problem solving
- Event driven programming in java
- Elementary programming in java
- Java asynchronous programming
- Java structured programming
- Arne kutzner
- New program khan academy
- Event driven programming in java
- Defensive programming java
- Java refresher course
- Java games programming
- Java programming symbols
- Java introduction to problem solving and programming
- Elementary programming in java
- Java database programming
- Asynchronous programming in java
- Conclusion of java