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

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Index Exception handling Exception In Java Exception Types
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Java Exceptions. Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: Often in computing,
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
For use of Cleveland State's IST410 Students only 1 Exception.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
Java Programming Transparency No. 1-1 Java Exception Handling Cheng-Chia Chen.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Io package as Java’s basic I/O system continue’d.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Object Oriented Programming with Java (150704).  Throwable Exception (This class will catch exceptions generated by prog.) (Create your own custom exception.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
CS102 – Exceptions David Davenport Latest: May 2015
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Web Design & Development Lecture 7
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Tutorial MutliThreading.
Exceptions 10-May-19.
Java Basics Exception Handling.
Exception Handling.
Exceptions and Exception Handling
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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