Java Exception Very slightly modified from K.P. Chow

Slides:



Advertisements
Similar presentations
Yoshi
Advertisements

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
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.
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.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
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 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.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
COMP Exception Handling Yi Hong June 10, 2015.
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.
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.
Practice Session 9 Exchanger CyclicBarrier Exceptions.
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.
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.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
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.
Lec.11 (Chapter 11) Exception Jiang (Jen) ZHENG July 13 th, 2005.
Java Exceptions a quick review….
Chapter 14 – Exception Handling
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Introduction to OO Program Design
CS102 – Exceptions David Davenport Latest: May 2015
COMPSCI 230 S Programming Techniques
CS Week 10 Jim Williams, PhD.
Handling Exceptions.
Advanced Programming Behnam Hatami Fall 2017.
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.
ATS Application Programming: Java Programming
Exception Handling.
Lecture 9: Exceptions in Java CS201j: Engineering Software
Web Design & Development Lecture 7
Java Exception Very slightly modified from K.P. Chow
Exception Handling in Java
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
Exception Handling Contents
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.
Java Basics Exception Handling.
Exception Handling.
Chapter 15 – Exception Handling
Presentation transcript:

Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)

An event that occurs during the execution of a program that disrupts the normal flow of instructions Exception Example public class test { public static void main(String[] args) { int temp[] = new int[3]; temp[3] = 4; ….. } Error detected in runtime. javac test.java C:\> java test Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException at test.main(test.java:4)

public static void main(String[] args) { Example import java.io.*; public class test2 { public static void main(String[] args) { File input = new File(“input.txt”); FileInputStream in = new FileInputStream(input); ….. } C:\> javac test.java test2.java:5: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown FileInputStream in = new FileInputStream(input); ^ 1 error Detected in compile time

Mechanism for handling exceptions method4? Exception handler in Y Catch the exception Call Stack Example method1 { call method2; } method2 { call method3; method3 { call method4; method4 { ………. N method3? Y N method2? Y N method1? method3 Y method2 N Sys. stops method1 Throwing an exception Create an exception object and runtime system take over Runtime system Exception!!

Two Types of Exception runtime exceptions checked exceptions run time checking occurs within Java runtime system occurs outside the control of Java runtime system compile time checking e.g. Division by zero ArrayIndexOutofBounds e.g. IO exception FileNotFoundException implement exception handler Must be caught or thrown Q: what exception to worry For each method? Notify calling methods

Exception Hierarchy (part of) IOException InterruptedException RuntimeException NullPointerException ClassCastException

Exceptions can be thrown by a method Exception thrown by this method Exception thrown by called methods Leave it to calling method to handle Example(1) in java.io.InputStream class, public int read(byte[], b) throws IOException (Exception Type, must be a class inherits from the “Throwable” class) similar for read( ) Example(2) import java.io.*; public void m1( ){ int b = System.in.read( ); } Error!!! m1 has to either catch or throw IOException

Example(3) import java.io.*; public void m1( ){ m2( ); } public void m2( ){ m3( ); public void m3( ) throws IOException { int b = System.in.read( ); public void m1( ) throws IOException { m2( ); } Error!! m1 has to either catch or throw IOException public void m2( ) throws IOException { m3( ); } Error!! m2 has to either catch or throw IOException Compile ok, but do not handle the exception….

import java.util.Vector; import java.io.*; import java.util.Vector; public class ListOfNumbers { private Vector v; private static final int SIZE = 10; public ListOfNumbers( ) { v = new Vector(SIZE); for (int i=0; i < SIZE; i++) { v.addElement(new Integer(i)); } public void writeList() { PrintWriter out = new PrintWriter(new FileWriter(“out.txt”)); for (int i=0; i<SIZE; i++) { out.println(v.elementAt(i)); out.close(); NOT required to catch or you can REQUIRED to catch or throw public FileWriter(String fileName) throws IOException runtime exception: ArrayIndexOutOfBoundsException

Catch the exception – exception handler statements that may throw exceptions try { block of statements } catch (ExceptionType name) { exception handler 1 exception handler 2 } Each catch block is an exception handler taking care of different exceptions

public void writeList() { PrintWriter out = new PrintWriter(new FileWriter(“out.txt”)); for (int i=0; i<SIZE; i++) { out.println(v.elementAt(i)); } out.close(); public void writeList() { try { PrintWriter out = new PrintWriter(new FileWriter(“out.txt”)); for (int i=0; i<SIZE; i++) { out.println(v.elementAt(i)); } out.close( ); } catch (ArrayIndexOutOfBoundsException e) { System.err.println(“Caught ArrayIndexOutOfBoundsException”); } catch (IOException e) { System.err.println(“Caught IOException”);

public void writeList() { try { PrintWriter out = new PrintWriter(new FileWriter(“out.txt”)); for (int i=0; i<SIZE; i++) { out.println(v.elementAt(i)); } out.close( ): } catch (ArrayIndexOutOfBoundsException e) { System.err.println(“Caught ArrayIndexOutOfBoundsException”); } catch (IOException e) { System.err.println(“Caught IOException”); May not get executed! use a finally block (always will execute, even if we jump out of try block)

How about if writeList do public void writeList() { try { PrintWriter out = new PrintWriter(new FileWriter(“out.txt”)); for (int i=0; i<SIZE; i++) { out.println(v.elementAt(i)); } } catch (ArrayIndexOutOfBoundsException e) { System.err.println(“Caught ArrayIndexOutOfBoundsException”); } catch (IOException e) { System.err.println(“Caught IOException”); } finally { if (out != null) { out.close( ); If throw, an old exception might be lost How about if writeList do not want to handle it? public void writeList() throws IOException, ArrayIndexOutOfBoundsException { public void writeList() throws IOException {

Can I create my own Exception classes? Object Throwable Exception RuntimeException differentiate your exceptions from existing ones…. Example public class NewException extends Exception { ……} Example public class NewException extends RuntimeException { ……} Not required to catch or throw

Example: Assign 1 … public static void main( String[] args) { int j; j = Integer.parseInt(args[0]); ….. } in Integer class: public static int parseInt(String s) throws NumberFormatException; public static void main( String[] args) { int j; try { j = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.out.println(“wrong input format”); } …..

exception.printStackTrace() prints: Error message Exception class name Descriptive string stored in the exception throw new Exception(“descriptive string”); List of methods that had not completed execution exception.getMessage() Returns the descriptive string stored in the exception exception.getStackTrace() Used to output to other forms (see next page)

StackTraceElement[] trace = exception.getStackTrace(); For(int I=0; I<trace.length;I++){ StackTraceElement current = trace[I]; System.out.print(current.getClassName() + “\t” ); System.out.print(current.getFileName() + “\t” ); System.out.print(current.getLineNumber () + “\t” ); System.out.print(current.getMethodName() + “\n” ); }

Storing chained exception info. Catch one- throw another, but can keep the info of the old one. catch (NumberFormatException e) { throw new Exception(“descriptive string”,e); }