17
Lecture 2 Exception handling Advanced Java Programming 1 dr inż. Wojciech Bieniecki [email protected] http://wbieniec.kis.p.lodz.pl

Lecture 2 Exception handling Advanced Java Programming 1 dr inż. Wojciech Bieniecki [email protected]

Embed Size (px)

Citation preview

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

Lecture 2Exception handling

Advanced Java Programming

1

dr inż. Wojciech [email protected]://wbieniec.kis.p.lodz.pl

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

ExceptionsAn 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

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

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

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

Common types of exceptionsIn the package java.io.*:EOFException – end of the fileFileNotFoundException – no fileInterruptedIOException – disk operation interruptionIOException – 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

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

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

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

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

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

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

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

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

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

Forwarding of exception handlingto 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

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

Forwarding of exception handlingto 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

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

The flow of handlingthe 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.

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).11

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

Finally clause

Was an exception?

Break try go to catch clause

Run thefinally clause

Run thefinally clause

Jump outsidethe 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

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

Own exceptionsExceptions 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

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

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

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

Exceptions - exampleclass 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

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

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

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

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