Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 2 Exception handling Advanced Java Programming 1 dr inż. Wojciech Bieniecki

Similar presentations


Presentation on theme: "Lecture 2 Exception handling Advanced Java Programming 1 dr inż. Wojciech Bieniecki"— Presentation transcript:

1 Lecture 2 Exception handling Advanced Java Programming 1 dr inż. Wojciech Bieniecki wbieniec@kis.p.lodz.pl http://wbieniec.kis.p.lodz.pl

2 Exceptions An exception arises from some unexpected error. An exception is raised. An exception is handled. Exceptions are objects of exception classes. Every exception name is the name of the class. Inheritance hierarchy begins at the base class Throwable. Fatal errors are derived from its subclass Error. These more daily (to use) are subclasses of class Exception. 2

3 Types of exceptions Other exceptions are controlled, which means that: 1.Method of raising those exceptions mention them explicitly in their declaration in a throws clause 2.These methods can raise only exceptions mentioned in a throws clause (or exceptions of their subclasses), 3.References to these methods require explicit exception handling by: through the construction of the try – catch, by listing the exception in a throws clause of our method (the one that refers to a method that may raise an exception), and "shift" exception handling to the caller of our method. Exceptions derived from RuntimeException and Error classes are uncontrollable: means the run time errors (less serious and serious), can occur anywhere in your code. 3

4 Common types of exceptions In the package java.io.*: EOFException – end of the file FileNotFoundException – no file InterruptedIOException – disk operation interruption IOException – super class for the exceptions In the package java.lang.*: ArithmeticException – exception of the arithmetic operations (division by zero), ArrayIndexOutOfBoundsException – exceeding the range of the array, ClassNotFoundException – bad class name, Exception – super class for the exceptions. Some exemplary errors: NoSuchFieldError – no such field in the class, NoSuchMethodError – no much method in the class, OutOfMemoryError - not enough memory. 4

5 The scheme of exception handling int a, b, c; String s; try { // in the try block apprehend the instructions, which may cause an exception a = b/c; // if c == O, ArithmeticException will be raisen // NOTE! It works only for integers s = Integer.toString(a); } catch(ArithmeticException ex) { //the exception is handled by catch s = "*" ; } 5

6 Exceptions generated and handled in one method class App extends Frame { String cname; public static void main(String[] args) { App app = new App(); try{ app.cname = args[0];} catch(IndexOutOfBoundsException exc) { // you dont need to handle it app.cname = "java.awt.TextField"; } app.initialize(); } Example: An application that displays the component whose name you enter as a command line parameter 6

7 Exceptions generated and handled in one method void initialize() { Component comp = null; try { Class c = Class.forName(cname); comp = (Component) c.newInstance(); } catch(ClassNotFoundException exc) { // from forName method – must be handled System.out.println("Class " + cname + " not found"); System.exit(1); } catch(IllegalAccessException exc) { // from newInstance method – must be handled System.out.println("illegal access to class " + cname); System.exit(1); } 7

8 Exceptions generated and handled in one method String txt = "Alice has a cat"; if (comp instanceof TextComponent) ((TextComponent)comp).setText(txt); else if (comp instanceof Label) ((Label) comp).setText(txt); else if (comp instanceof Button) ((Button) comp).setLabel(txt); add(comp); pack(); setVisible(true); } 8

9 Forwarding of exception handling to the calling class App extends Frame { String cname; public static void main(String[] args) { App app = new App(); try { app.cname = args[0]; } catch(IndexOutOfBoundsException exc) { app.cname = "java.awt.TextField"; } try { app. initialize(); } catch(Exception exc) { //only Exception – not recommended System.out.println("Exception! "+ exc); System.exit(1); } 9

10 Forwarding of exception handling to the calling void initialize() throws // pass to the calling ClassNotFoundException, IllegalAccessException, InstantiationException { Class c = Class.forName(cname); Component comp=(Component)c.newInstance(); String txt = "Ala ma kota"; if (comp instanceof TextComponent) ((TextComponent)comp).setText(txt); else if (comp instanceof Label) ((Label)comp).setText(txt); else if (comp instanceof Button) ((Button)comp).setLabel(txt); add(comp); // here may be IllegalArgumentException pack(); setVisible(true); } 10

11 The flow of handling the exception Subsequent instructions are executed try block If there is an exception, the execution of the try block is terminated. ontrol is passed to the first catch clause in the order, the "argument" (type exception) fits the resulting type of exception Hence an important conclusion: first, give MORE SPECIFIC TYPES OF EXCEPTIONS. ontrol is passed to the first catch clause in the order, the "argument" (type exception) fits the resulting type of exception Hence an important conclusion: first, give MORE SPECIFIC TYPES OF EXCEPTIONS. Other catch clauses are not "run". The catch clause that handles the exception can do many things, including change the control sequence (eg, by return, raise a new exception using the throw statement). If you do not change the control sequence, the execution of the program is continued in the finally clause, or if it does not exist - from the next instruction after try block (after the last clause- catch block). The catch clause that handles the exception can do many things, including change the control sequence (eg, by return, raise a new exception using the throw statement). If you do not change the control sequence, the execution of the program is continued in the finally clause, or if it does not exist - from the next instruction after try block (after the last clause- catch block). 11

12 Finally clause Was an exception? Break try go to catch clause Run the finally clause Jump outside the block YES NO boolean method(...) { try { /*instructions that may cause an exception*/ } catch(Exception e) { return false; } finally { /* clean up: close the connection*/ } return true; } 12

13 Own exceptions Exceptions are objects of classes derived from Throwable. To create a custom exception, you must define the class. By convention, we inherit the Exception class (a subclass of Throwable). void naszaMetoda() throws NaszWyj {..... if(błąd) throw new NaszWyj(ew_Pairm_konstruktora_z_info_o_błędzie); } class NaszWyj extends Exception {... } Exception Reporting: if our method can raise NaszWyj, it must specify it in the declaration our method checks for error conditions, If an error has occurred - creates an exception and reports it using the throw statement: 13

14 Exceptions - example import java.awt.*; import java.awt.event.*; class NotValidZipException extends Exception { // exception class public String msg = "A valid ZIP code has a format nn-nnn"; NotValidZipException(String s) {// Constructor msg = "Niepoprawny kod: "+s+". "+msg; } 14

15 Exceptions - example class ZipField extends TextField{// class of component ZipField(){ super(); } ZipField(String s) {super(s); } ZipField(int n) {super(n); } public String getZip() throws NotValidZipException { final int N = 6, P = 2; String zip = getText(); boolean valid = true; char[] c = zip.toCharArray(); if (c.length != N || c[P] != '-') valid = false; for (int i = 0; i<N && valid; i++) { if (i == P) continue; if (!Character.isDigit(c[i])) valid = false; } if (!valid) throw new NotValidZipException(zip); return zip; } 15

16 Exceptions - example class Exc3 extends Frame implements ActionListener { ZipField zf = new ZipField(10); public static void main(String[] args) { new Exc3(); } Exc3() { setLayout(new FlowLayout()); Button b = new Button("Enter"); b.addActionListener(this); add(zf); add(b); pack(); setVisible(true); } 16

17 Exceptions - example public void actionPerformed(ActionEvent e) { String txt = null; try { txt = zf.getZip(); } catch(NotValidZipException exc) { System.out.println(exc.msg); return; } System.out.println("You’ve entered the code : " + txt); } 17


Download ppt "Lecture 2 Exception handling Advanced Java Programming 1 dr inż. Wojciech Bieniecki"

Similar presentations


Ads by Google