EXCEPTIONS. Java Programming

Similar documents
EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring 2017

More on Exception Handling

Fundamentals of Object Oriented Programming

ECE 122. Engineering Problem Solving with Java

More on Exception Handling

Exceptions Handling Errors using Exceptions

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

What are Exceptions?

Sri Vidya College of Engineering & Technology Question Bank

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Exceptions - Example. Exceptions - Example

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Chapter 3 Java Exception

National University. Faculty of Computer Since and Technology Object Oriented Programming

Full file at Chapter 2 - Inheritance and Exception Handling

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Correctness and Robustness

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Exception-Handling Overview

EXCEPTION HANDLING. Summer 2018

Programming II (CS300)

6.Introducing Classes 9. Exceptions

Exceptions and Error Handling

Exceptions. CSC207 Winter 2017

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Programming II (CS300)

Data Structures. 02 Exception Handling

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

Lecture 19 Programming Exceptions CSE11 Fall 2013

COMP-202 Unit 9: Exceptions

CS159. Nathan Sprague

Introduction to Software Design

ITI Introduction to Computing II

17. Handling Runtime Problems

C16b: Exception Handling

ITI Introduction to Computing II

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Exception Handling CSCI 201 Principles of Software Development

Chapter 14. Exception Handling and Event Handling ISBN

COE318 Lecture Notes Week 10 (Nov 7, 2011)

COMP-202 Unit 9: Exceptions

Projeto de Software / Programação 3 Tratamento de Exceções. Baldoino Fonseca/Márcio Ribeiro

Object Oriented Programming

CS193j, Stanford Handout #25. Exceptions

Input-Output and Exception Handling

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

Introduction to Java. Handout-3a. cs402 - Spring

Exceptions and Libraries

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Internal Classes and Exceptions

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

13: Error Handling with Exceptions. The basic philosophy of Java is that "badly formed code will not be run."

Here is a hierarchy of classes to deal with Input and Output streams.

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

2.6 Error, exception and event handling

Object Oriented Programming Exception Handling

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1

CSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

CS 11 java track: lecture 3

Java. Error, Exception, and Event Handling. Error, exception and event handling. Error and exception handling in Java

Exceptions in Java

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

15CS45 : OBJECT ORIENTED CONCEPTS

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Exception Handling. Exception Handling

CSC 1214: Object-Oriented Programming

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

Abstract Classes, Exceptions

For more details on SUN Certifications, visit

Administrivia. CPSC Winter 2008 Term 1. Department of Computer Science Undergraduate Events

Std 12 Lesson-10 Exception Handling in Java ( 1

Errors and Exceptions

Binary search. int index = Collections.binarySearch(list, element);

Transcription:

8 EXCEPTIONS 271

Objectives Define exceptions Exceptions 8 Use try, catch and finally statements Describe exception categories Identify common exceptions Develop programs to handle your own exceptions 272

Exceptions The exception class defines mild error conditions that your program encounters. Exceptions 8 Exceptions can occur when The file you try to open does not exist The network connection is disrupted Operands being manipulated are out of prescribed ranges The class file you are interested in loading is missing An error class defines serious error conditions 273

Exceptions 8 1 public class HelloWorld { 2 public static void main (String args[]) { 3 int i = 0; 4 5 String greetings [] = { 6 "Hello world!", 7 "No, I mean it!", 8 "HELLO WORLD!!" 9 ; 10 11 while (i < 4) { 12 System.out.println (greetings[i]); 13 i++; 14 15 16 274

Exceptions 8 Hello world! No, I mean it! HELLO WORLD!! java.lang.arrayindexoutofboundsexception at HelloWorld.main(HelloWorld.java:12) Exception in thread "main" Process Exit... 275

The try and catch Statements try { // code that might throw a particular exception Exceptions 8 catch (MyExceptionType e) { // code to execute if a MyExceptionType exception is thrown catch (Exception e) { // code to execute if a general Exception exception is thrown 276

Call Stack Mechanism If an exception is not handled in the current try/catch block, it's thrown to the caller of that method. Exceptions 8 If the exception gets back to the main method and is not handled there, the program is terminated abnormally. 277

Call Stack Mechanism Exceptions 8 Consider a case where a method calls another method named openconnection(), and this, in turn calls another method named sendrequest(). If an exception occurs in sendrequest(), it is thrown back to openconnection(), where a check is made to see if there is a catch for that type of exception. if no catch exists in openconnection(), the next method in the call stack, main(), is checked. if the exception is not handled by the last method on the call stack, then a runtime error occurs and the program stops executing. 278

The finally Statement Exceptions 8 What if we have some clean up to do before we exit our method from one of the catch clauses? To avoid duplicating the code in each catch branch and to make the cleanup more explicit, Java supplies the finally clause. A finally clause can be added after a try and any associated catch clauses. Any statements in the body of the finally clause are guaranteed to be executed, no matter why control leaves the try body: next slide 279

Exceptions 8 try { // Do something here catch ( FileNotFoundException e ){... catch ( IOException e ) {... catch ( Exception e ) {... finally { // Cleanup here 280

If the statements in the try execute cleanly, or even if we perform a return, break, or continue, the statements in the finally clause are executed. To perform cleanup operations, we can even use try and finally without any catch clauses: Exceptions 8 try { // Do something here return; finally { System.out.println( Do not ignore me!"); 281

Exceptions 8 public class HelloWorldRevisited { public static void main (String args[]) { int i = 0; String greetings [] = { "Hello world!", "No, I mean it!", "HELLO WORLD!! ; while (i < 4) { try { System.out.println (i+" "+greetings[i]); catch (ArrayIndexOutOfBoundsException e){ System.out.println("Re-setting Index Value"); break; finally { System.out.println("This is always printed"); i++; // end while() // end main() 282

Exception Categories Exceptions 8 Error indicates a severe problem from which recovery is difficult, if not impossible. An example is running out of memory. A program is not expected to handle such conditions. RuntimeException indicates a design or implementation problem. That is, it indicates conditions that should never happen if the program is operating properly.an ArrayOutOfBoundsException exception, for example, should never be thrown if the array indices do not extend past the array bounds. This would also apply, for example, to referencing a null object variable. Other exceptions indicate a difficulty at runtime that is usually caused by environmental effects and can be handled. Examples include a file not found or invalid URL exceptions. Because these usually occur as a result of user error, you are encouraged to handle them. 283

Exceptions 8 284

Exceptions 8 285

Exceptions 8 286

ArithmeticException Common Exceptions Exceptions 8 int i = 12 / 0 ; NullPointerException Date d = null ; System.out.println(d.toString()) ; NegativeArraySizeException ArrayIndexOutOfBoundsException SecurityException Access a local file Open a socket to the host that is not the same host that served the applet Execute another program in runtime environment 287

The Handler or Declare Rule Handle exceptions by using the try-catch-finally block Exceptions 8 Declare that the code causes an exception by using the throws clause A method may declare that it throws more than one exception You do not need to handle or declare runtime exceptions or errors. 288

Method Overriding and Exceptions The overriding method: Exceptions 8 Can throw exceptions that are subclasses of the exceptions being thrown by the overridden method For example, if the superclass method throws an IOException, then the overriding method can throw an IOException, a FileNotFoundException (a subclass of IOException), but not an Exception (the superclass of IOException) 289

Exceptions 8 public class TestA { public void methoda() throws RuntimeException { // do some number crunching public class TestB1 extends TestA { public void methoda() throws ArithmeticException { // do some number crunching public class TestB2 extends TestA { public void methoda() throws Exception { // do some number crunching 290

Exceptions 8 public class TestMultiA { public void methoda() throws IOException, RuntimeException { // do some IO stuff public class TestMultiB1 extends TestMultiA { public void methoda() throws FileNotFoundException, UTFDataFormatException, ArithmeticException { // do some number crunching 291

import java.io.* ; import java.sql.* ; Exceptions 8 public class TestMultiB2 extends TestMultiA { public void methoda() throws FileNotFoundException, UTFDataFormatException, ArithmeticException, SQLException { // do some IO, number crunching, and SQL stuff 292

Exceptions 8 public class ServerTimedOutException extends Exception { private int port; public ServerTimedOutException (String reason,int port){ super(reason); this.port = port; public int getport() { return port; To throw an exception of the above type, write throw new ServerTimedOutException( Could not connect,60) ; 293

Exceptions 8 public void connectme(string servername) throws ServerTimedOutException { int success; int porttoconnect = 80 ; success = open(servername,porttoconnect) ; if( success == -1 ) throw new ServerTimedOutException( Could not connect, porttoconnect); public void findserver() { try { connectme(defaultserver) ; catch (ServerTimedOutException e) { System.out.println( Server timed out, trying alternative ) ; try{ connectme( alternativeserver) ; catch (ServerTimedOutException e1) { System.out.println( Error : + e1.getmessage() + connecting to port + e1.getport()) ; 294

Exceptions 8 1 // Fig. 14.10: UsingExceptions.java 2 // Demonstrating the getmessage and printstacktrace 3 // methods inherited into all exception classes. 4 public class UsingExceptions { 5 public static void main( String args[] ) 6 { 7 try { 8 method1(); 9 10 catch ( Exception e ) { 11 System.err.println( e.getmessage() + "\n" ); 12 13 e.printstacktrace(); 14 15 16 public static void method1() throws Exception 17 { 18 method2(); 19 20 21 public static void method2() throws Exception 22 { 23 method3(); 24 main 25 public static void method3() throws Exception 26 { 27 throw new Exception( "Exception thrown in method3" ); 28 29 Call method1, which calls method2, which calls method3, which throws an exception. getmessage prints the String the Exception was initialized with. printstacktrace prints the methods in this order: method3 method2 method1 (order they were called when exception occurred) 295

Exceptions 8 Exception thrown in method3 java.lang.exception: Exception thrown in method3 at UsingExceptions.method3(UsingExceptions.java:28) at UsingExceptions.method2(UsingExceptions.java:23) at UsingExceptions.method1(UsingExceptions.java:18) at UsingExceptions.main(UsingExceptions.java:8) 296