CS203 Java Object Oriented Programming Errors and Exception Handling.

Slides:



Advertisements
Similar presentations
„Exceptions”. Exceptions Handling errors with exceptions Golden rule of programming: Errors occur in software programs. What really matters is what happens.
Advertisements

Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 13 Exception.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
COMP201 Java Programming Topic 7: Exceptions Reading: Chapter 11.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Exception Handling (in a nutshell). 2 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
Java Software Solutions Foundations of Program Design Sixth Edition
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 14 Exception Handling and Text.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 12 Exception Handling and Text.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Preventing and Correcting Errors
1 Chapter 18 Exception Handling. 2 Motivations F Program runs into a runtime error –program terminates abnormally F How can you handle the runtime error.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Exception Handling.
Exception Handling. Definition  The term exception is shorthand for the phrase "exceptional event.“  An exception is an event, which occurs during the.
CIS 270—Application Development II Chapter 13—Exception Handling.
Slides Credit Umair Javed LUMS Web Application Development.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
COMP Exception Handling Yi Hong June 10, 2015.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Exceptions and Assertions Chapter 15 – CSCI 1302.
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 Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 15 Exceptions and Assertions Nothing is impossible.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
CS 112 Programming 2 Lecture 08 Exception Handling & Text I/O (1)
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
OOP Tirgul 7. What We’ll Be Seeing Today  Packages  Exceptions  Ex4 2.
Object Throwable ErrorException RuntimeException.
Java Exceptions a quick review….
Chapter 13 Exception Handling
Exceptions In this lecture:
Chapter 12 Exception Handling And Text IO
Chapter 13 Exception Handling
Topic: Exception Handling
Chapter 12 Exception Handling and Text IO
Chapter 12 Exception Handling and Text IO
Chapter 12 Exception Handling
Chapter 11 Exception Handling and Text I/O
Chapter 12 Exception Handling and Text IO
Chapter 13 Exception Handling
Intro to Exceptions (c) Eraj Basnayake
Chapter 12 Exception Handling and Text IO Part 1
Chapter 12 Exception Handling and Text IO Part 2
Exception Handling.
Presentation transcript:

CS203 Java Object Oriented Programming Errors and Exception Handling

Examples of Exceptions ArrayIndexOutOfBoundException NumberFormatException int a[] = new int[10]; for( int i=0 ; i <= a.length ; ++i ) a[i] = i; String s = “7.3”; int n = Integer.parseInt( s );

Runtime Errors Errors happened when the program is running, e.g. Access an element outside array boundary Read a file which doesn’t exist User input errors Runtime error handling Error codes Exceptions

Exception Types

System Errors System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.

Exceptions Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.

Runtime Exceptions RuntimeException is caused by programming errors, such as bad casting, accessing an out- of-bounds array, and numeric errors.

Checked Exceptions vs. Unchecked Exceptions RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions.

Unchecked Exceptions In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example, a NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array. These are the logic errors that should be corrected in the program. Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate you to write code to catch unchecked exceptions.

Checked or Unchecked Exceptions Unchecked exception.

Error Codes // n >= 1 int factorial( int n ) { // return an error code if( n < 1 ) return –1; int fact = 1; for( int i=1 ; i <= n ; ++i ) fact *= i; return fact; } int f = factorial(x); if( f == -1 ) // error handling { System.err.println( “error!”); System.exit(1); } else // regular code { // do something with f }

Raise An Exception – throw int factorial( int n ) throws LessThanOneException { if( n < 1 ) throw new LessThanOneException(); int fact = 1; for( int i=1 ; i <= n ; ++i ) fact *= i; return fact; }

A Closer Look at Throw int factorial( int n ) throws LessThanOneException { if( n < 1 ) throw new LessThanOneException(); int fact = 1; for( int i=1 ; i <= n ; ++i ) fact *= i; return fact; } Return type Returned value Exception type Exception value

Exception Class Pre-defined in Java All exception classes must inherit from this class Important methods Exception() Exception( String msg ) String getMessage() void printStackTrace()

Create An Exception Class public class LessThanOneException extends Exception { public LessThanOneException() { super(); } public LessThanOneException( String msg ) { super(msg); }

Handle An Exception – try and catch try// regular code { int f = factorial(n); // do something with f } catch( LessThanOneException e ) // error handling { System.err.println( “error!” ); System.exit(1); }

Using Exceptions In a method where an error may occur Declare exception type in method header: throws Raise an exception if the error occurs: throw In the calling method Handle the exception  Enclose regular code in a try block  Enclose error handling code in a catch block Do not handle the exception  Declare the exception in method header

Throw Multiple Exceptions public void foo() throws ExceptionA, ExceptionB, ExceptionC { … throw new ExceptionA(“Bad thing A”); … throw new ExceptionB(“Bad Thing B”); … throw new ExceptionC(“Bad Thing C”); }

Catch Multiple Exceptions Or, if we don’t need to distinguish exactly which type of exception occurs try { foo(); } catch( ExceptionA ea ) { // do something } catch( ExceptionB eb ) { // do something } catch( ExceptionC ec ) { // do something } try { foo(); } catch( Exception e ) { System.err.println( e.getMessage() ); System.exit(1); }

A More Complex Example readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; }

Handling Errors with Error Code errorCodeType readFile { errorCode = 0; open the file; If (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; }

Handling Errors with Exceptions readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch(fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } }

Advantages of Exceptions Separate error handling code with from regular code Propagate errors up the call stack Group error types and error differentiation

Error Propagation Example method1 { try { call method2; } catch (exception) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; }

Error Grouping and Differentiation Example

The finally Clause try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; }

Cautions When Using Exceptions Exception handling separates error- handling code from normal programming tasks, thus making programs easier to read and to modify. Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods.

When to Throw Exceptions An exception occurs in a method. If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it.

When to Use Exceptions When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null"); }

When to Use Exceptions is better to be replaced by if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null");

Creating Custom Exception Classes F Use the exception classes in the API whenever possible. F Create custom exception classes if the predefined classes are not sufficient. F Declare custom exception classes by extending Exception or a subclass of Exception.