Java Computer Industry Lab. 1 Programming Java Exception Handling Incheon Paik.

Slides:



Advertisements
Similar presentations
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
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)
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)
Index Exception handling Exception In Java Exception Types
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
For use of Cleveland State's IST410 Students only 1 Exception.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
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.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
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 CIS 304 Intermediate Java Programming for Business.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other Error Handling Techniques 14.4The Basics.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Program Errors Syntax errors Logic errors
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.
Peyman Dodangeh Sharif University of Technology Spring 2015.
Lecture 2 Exception handling Advanced Java Programming 1 dr inż. Wojciech Bieniecki
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
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.
Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
1 cuberoot /* Solve f(x) = x*x*x-5 = 0 f'(x) = 3x^2 */ public class cuberoot{ public static void main(String args[]){ double error= ; double x0.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
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.
1 1. Normal and exceptional control flow 2. Java exception types 3. Exception handling syntax 4. Inheritance.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Recitation 3 2D Arrays, Exceptions. 2D arrays 2D Arrays Many applications have multidimensional structures: ●Matrix operations ●Collection of lists ●Board.
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.
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.
CSE 1201 Object Oriented Programming
Chapter 14 – Exception Handling
Exceptions: When things go wrong
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction to OO Program Design
COMPSCI 230 S Programming Techniques
Handling Exceptions.
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 OR ERROR HANDLING.
OBJECT ORIENTED PROGRAMMING
Java Exception Very slightly modified from K.P. Chow
Java Exception Very slightly modified from K.P. Chow
Managing Errors and Exceptions
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
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.
Exception Objects An exception is an abnormal condition that arises in a code sequence at rum time. Exception is a way of signaling serious problem.
Presentation transcript:

Java Computer Industry Lab. 1 Programming Java Exception Handling Incheon Paik

Java Computer Industry Lab. 2 Contents Contents Exception Handling Catch Block Searches The throw Statement Exception and Error Classes The throws Clause Custom Exceptions

Java Computer Industry Lab. 3 Exception Handling class DivideByZero { public static void main(String args[]) { a(); } static void a() { b(); } static void b() { c(); } static void c() { d(); } static void d() { int i = 1; int j = 0; System.out.println(i / j); } Result : Exception in thread "main" java.lang.ArithmeticException: / by zero at DivideByZero.d(DivideByZero.java:22) at DivideByZero.c(DivideByZero.java:16) at DivideByZero.b(DivideByZero.java:12) at DivideByZero.a(DivideByZero.java:8) at DivideByZero.main(DivideByZero.java:4)

Java Computer Industry Lab. 4 Exception Handling try { // try block } catch (ExceptionType1 param1) { // Exception Block } catch (ExceptionType2 param2) { // Exception Block } …… catch (ExceptionTypeN paramN) { // Exception Block } finally { // finally Block } Exception Handling Codes that have some possibilities to generate exception(s). Execute the codes here when the corresponding exception occurred. Do always

Java Computer Industry Lab. 5 Exception Handling class Divider { public static void main(String args[]) { try { System.out.println("Before Division"); int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]); System.out.println(i / j); System.out.println("After Division"); } catch (ArithmeticException e) { System.out.println("ArithmeticException"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndex" + "OutOfBoundsException"); } catch (NumberFormatException e) { System.out.println("NumberFormatException"); } Result : java Divider Before Division ArrayIndexOutOfBoundsException Finally block finally { System.out.println("Finally block"); } Result : java Divider 1 0 Before Division ArithmeticException Finally block

Java Computer Industry Lab. 6 Catch Block Searches class CatchSearch { public static void main(String args[]) { try { System.out.println("Before a"); a(); System.out.println("After a"); } catch (Exception e) { System.out.println("main: " + e); } finally { System.out.println("main: finally"); } public static void a() { try { System.out.println("Before b"); b(); System.out.println("After b"); } catch (ArithmeticException e) { System.out.println("a: " + e); } finally { System.out.println("a: finally"); } Result : Before a Before b Before c Before d d: finally c: finally b: java.lang.ArrayIndexOutOfBoundsException: 10 b: finally After b a: finally After a main: finally public static void b() { try { System.out.println("Before c"); c(); System.out.println("After c"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("b: " + e); } finally { System.out.println("b: finally"); } public static void c() { try { System.out.println("Before d"); d(); System.out.println("After d"); } catch (NumberFormatException e) { System.out.println("c: " + e); } finally { System.out.println("c: finally"); } public static void d() { try { int array[] = new int[4]; array[10] = 10; } catch (ClassCastException e) { System.out.println("d: " + e); } finally { System.out.println("d: finally"); }

Java Computer Industry Lab. 7 The throw Statement throw object; The throw Statement catch (ExceptionType param) { …. throw param; ….. } Exception Object in Argument throw new ExceptionType(args); Throw to new Exception Object Use the statement when we generate an exception

Java Computer Industry Lab. 8 The throw Statement class ThrowDemo { public static void main(String args[]) { try { System.out.println("Before a"); a(); System.out.println("After a"); } catch (ArithmeticException e) { System.out.println("main: " + e); } finally { System.out.println("main: finally"); } public static void a() { try { System.out.println("Before b"); b(); System.out.println("After b"); } catch (ArithmeticException e) { System.out.println("a: " + e); } finally { System.out.println("a: finally"); } Result : Before a Before b Before c Before d Before division d: java.lang.ArithmeticException: / by zero d: finally c: java.lang.ArithmeticException: / by zero c: finally b: java.lang.ArithmeticException: / by zero b: finally After b a: finally After a main: finally public static void b() { try { System.out.println("Before c"); c(); System.out.println("After c"); } catch (ArithmeticException e) { System.out.println("b: " + e); } finally { System.out.println("b: finally"); } public static void c() { try { System.out.println("Before d"); d(); System.out.println("After d"); } catch (ArithmeticException e) { System.out.println("c: " + e); throw e; } finally { System.out.println("c: finally"); } public static void d() { try { int i = 1; int j = 0; System.out.println("Before division"); System.out.println(i / j); System.out.println("After division"); } catch (ArithmeticException e) { System.out.println("d: " + e); throw e; } finally { System.out.println("d: finally"); }

Java Computer Industry Lab. 9 The throw Statement class ThrowDemo2 { public static void main(String args[]) { try { System.out.println("Before a"); a(); System.out.println("After a"); } catch (Exception e) { System.out.println("main: " + e); } finally { System.out.println("main: finally"); } Result : Before a Before throw statement a: java.lang.ArithmeticException a: finally After a main: finally public static void a() { try { System.out.println("Before throw statement"); throw new ArithmeticException(); } catch (Exception e) { System.out.println("a: " + e); } finally { System.out.println("a: finally"); }

Java Computer Industry Lab. 10 Exception and Error Classes Throwable() Throwable(String message) Throwable Constructors Subclasses of Exception Class ClassNotFoundException IllegalAccessException InstantiationException InterruptedException NoSuchFieldException NoSuchMethodException RuntimeException String getMessage() getMessage() Method void printStackTrace() printStackTrace() Method Exception() Exception (String message) Exception Constructor Subclasses of RuntimeException ArrayIndexOutOfBoundsException ArithmeticException ClassCastException NegativeArraySizeException NullPointerException NumberFromatException SecurityException StringIndexOutOfBoundsException

Java Computer Industry Lab. 11 Exception and Error Classes class PrintStackTraceDemo { public static void main(String args[]) { try { a(); } catch (ArithmeticException e) { e.printStackTrace(); } public static void a() { try { b(); } catch (NullPointerException e) { e.printStackTrace(); } public static void b() { try { c(); } catch (NullPointerException e) { e.printStackTrace(); } public static void c() { try { d(); } catch (NullPointerException e) { e.printStackTrace(); } public static void d() { try { int i = 1; int j = 0; System.out.println(i / j); } catch (NullPointerException e) { e.printStackTrace(); } Result: java.lang.ArithmeticException: / by zero at PrintStackTraceDemo.d(PrintStackTraceDemo.java:43) at PrintStackTraceDemo.c(PrintStackTraceDemo.java:32) at PrintStackTraceDemo.b(PrintStackTraceDemo.java:23) at PrintStackTraceDemo.a(PrintStackTraceDemo.java:14) at PrintStackTraceDemo.main(PrintStackTraceDemo.java:5)

Java Computer Industry Lab. 12 The throws Clause consModifiers clsName(cparams) throws exceptions { // constructor body } throws Statement of Constructor class ThrowsDemo { public static void main(String args[]) { a(); } public static void a() { try { b(); } catch (ClassNotFoundException e) { e.printStackTrace(); } public static void b() throws ClassNotFoundException { c(); } public static void c() throws ClassNotFoundException { Class cls = Class.forName("java.lang.Integer"); System.out.println(cls.getName()); System.out.println(cls.isInterface()); } Result : Java.lang.Integer false mthModifiers rtype mthName(mparams) throws exceptions { // constructor body } throws Statement at a Method

Java Computer Industry Lab. 13 Custom Exceptions import java.util.*; class ExceptionSubclass { public static void main(String args[]) { a(); } static void a() { try { b(); } catch (Exception e) { e.printStackTrace(); } static void b() throws ExceptionA { try { c(); } catch (ExceptionB e) { e.printStackTrace(); } Execution: ExceptionA: We have a problem at ExceptionSubclass.c(ExceptionSubclass.java:31) at ExceptionSubclass.b(ExceptionSubclass.java:20) at ExceptionSubclass.a(ExceptionSubclass.java:11) at ExceptionSubclass.main(ExceptionSubclass.java:6) Subclass of Exception static void c() throws ExceptionA, ExceptionB { Random random = new Random(); int i = random.nextInt(); if (i % 2 == 0) { throw new ExceptionA("We have a problem"); } else { throw new ExceptionB("We have a big problem"); } class ExceptionA extends Exception { public ExceptionA(String message) { super(message); } class ExceptionB extends Exception { public ExceptionB(String message) { super(message); }

Java Computer Industry Lab. 14 Exercise Step 1 (Creating Some Methods for Exception) Slide 7,8,9, 12 static int thrower(String s) { try { if (s.equals("divide")) { // Write the code for raising Divide by Zero Exception } if (s.equals("null")) { // Write the code for raising NullPoint Exception } if (s.equals("test")) // Write the code for raising TestException return 0; } finally { // Some code for print out the current message }

Java Computer Industry Lab. 15 Exercise while(true) { try { istream = new FileInputStream(inputfilename); break; } catch(java.io.FileNotFoundException e) { System.out.print("File not found. Re-Enter file name : "); inputfilename = charStream.readLine().trim(); } } // end of while Step 2, Writing a Exception Handler 1 Slide # 7,8,9, 12 Step 3, Writing a Exception Handler 2