CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.

Slides:



Advertisements
Similar presentations
1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Yoshi
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
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.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
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.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions 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.
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.
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.
CS203 Java Object Oriented Programming Errors and Exception Handling.
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.
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 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.
Slides Credit Umair Javed LUMS Web Application Development.
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.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
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 in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
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.
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.
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:
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.
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.
Chapter 13 Exception Handling
Exceptions In this lecture:
Chapter 10 – Exception Handling
Chapter 12 Exception Handling And Text IO
MIT AITI 2003 Lecture14 Exceptions
Chapter 13 Exception Handling
Topic: Exception Handling
Chapter 12 Exception Handling and Text IO
Exceptions 10-Nov-18.
Chapter 7 Exceptions and Assertions
Exception Handling Chapter 9.
Chapter 12 Exception Handling
Exception Handling Chapter 9 Edited by JJ.
Web Design & Development Lecture 7
Chapter 13 Exception Handling
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.
Chapter 12 Exception Handling and Text IO Part 1
Presentation transcript:

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting error clears the score, and proves you wiser than before.” -- Arthur Guiterman

Errors Syntax errors arise because the rules of the language have not been followed. detected by the compiler. Logic errors leads to wrong results and detected during testing. arise because the logic coded by the programmer was not correct. Runtime errors Occur when the program is running and the environment detects an operation that is impossible to carry out.

Errors Code errors Divide by zero Array out of bounds Integer overflow Accessing a null pointer (reference) Programs crash when an exception goes untrapped, i.e., not handled by the program.

Runtime Errors

5 Exception An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. Exception = Exceptional Event

6 Exception Handling Java exception handling is a mechanism for handling exception by detecting and responding to exceptions in a systematic, uniform and reliable manner. Any exceptions not specifically handled within a Java program are caught by the Java run time environment

Exceptions A Method in Java throws exceptions to tell the calling code: “Something bad happened. I failed.” Exceptions are objects of Exception or Error class or their subclasses.

Exception Classes

Unchecked Exceptions

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.

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

Checked Exceptions

Exception Handling Keywords: 13

Java Library Exceptions Most Java routines throw exceptions. How do you know that the method you are going to call may throw an exception? You can look up the class documentation to see if a method throws exception Example: See the Scanner class methods at:

Handling Exceptions Java forces you to deal with checked exceptions. Two possible ways to deal:

Catching Exceptions try { //Statements that may throw exceptions } catch (Exception1 exVar1) { //code to handle exceptions of type Exception1; } catch (Exception2 exVar2) { // code to handle exceptions of type Exception2; }... catch (ExceptionN exVarN) { // code to handle exceptions of type exceptionN; } // statement after try-catch block Install an exception handler with try/ catch statement

Catching Exceptions

Getting Information from Exceptions Use instance methods of the java.lang.Throwable class Some useful methods: Example of printStackTrace() output String toString() Returns a short description of the exception String getMessage() Returns the detail description of the exception void printStackTrace() Prints the stacktrace information on the console java.lang.NullPointerException at MyClass.mash(MyClass.java:9) at MyClass.crunch(MyClass.java:6) at MyClass.main(MyClass.java:3)

Example public class Main { public static void main(String[] args) { java.io.PrintWriter output = null; try { output = new java.io.PrintWriter(“text.txt”); output.println(“Welcome to Java”); output.close(); } catch(java.io.IOException ex){ System.out.println(ex.toString()); ex.printStackTrace() ; }

Issues Must execute output.close() even if exception happens public class Main { public static void main(String[] args) { java.io.PrintWriter output = null; try { output = new java.io.PrintWriter(“text.txt”); output.println(“Welcome to Java”); output.close(); } catch(java.io.IOException ex){ ex.printStackTrace() ; }

Solution try { //Statements that may throw exceptions } catch (Exception1 exVar1) { //code to handle exceptions of type Exception1; } catch (Exception2 exVar2) { // code to handle exceptions of type Exception2; }... catch (ExceptionN exVar3) { // code to handle exceptions of type exceptionN; } finally { // optional // code executed whether there is an exception or not } Use finally clause for code that must be executed "no matter what"

Use finally block 22 public class Main { public static void main(String[] args) { java.io.PrintWriter output = null; try { output = new java.io. PrintWriter(“text.txt”); output.println(“Welcome to Java”); } catch(java.io.IOExcetion ex){ ex.printStackTrace() ; } finally { if (output != null) output.close(); }

finally block Executed when try block is exited in any of three ways: After last statement of try block (success). After last statement of catch clause, if this catch block caught an exception. When an exception was thrown in try block and not caught Executed even if there is a return statement prior to reaching the finally block 23

Throwing Exceptions public void setRadius(double newRadius) throws IllegalArgumentException IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); } When somebody writes a code that could encounter a runtime error, it creates an object of appropriate Exception class and throws it and must also declare it in case of checked exception

public class Circle { private double radius; private static int numberOfObjects = 0; public Circle() { this(1.0); } public Circle(double newRadius) throws IllegalArgumentException { setRadius(newRadius); numberOfObjects++; } public double getRadius() { return radius; } public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); } public static int getNumberOfObjects() { return numberOfObjects; }

public class TestCircle { public static void main(String[] args) { try { Circle c1 = new Circle(5); Circle c2 = new Circle(-5); Circle c3 = new Circle(0); } catch (IllegalArgumentException ex) { System.out.println(ex); } System.out.println("Number of objects created: " + Circle.getNumberOfObjects()); } Output: java.lang.IllegalArgumentException: Radius cannot be negative Number of objects created: 1

Creating Custom Exception Classes Create custom exception classes if the predefined classes are not sufficient. To declare custom exception class: F Create a class that extends Exception or a subclass of Exception. F It is good practice to add: F An argument-less constructor F Another constructor with one string type parameter

28 public class InvalidRadiusException extends Exception { private double radius; public InvalidRadiusException() { super(“invalid radius!”); } public InvalidRadiusException(double radius) { super("Invalid radius ”); this.radius = radius; } public double getRadius() { return radius; } } public class Circle { private double radius; private static int numberOfObjects = 0; public Circle() { this(1.0); } public Circle(double newRadius) throws InvalidRadiusException{ setRadius(newRadius); numberOfObjects++; } public void setRadius(double newRadius) throws InvalidRadiusException { if (newRadius >= 0) radius = newRadius; else throw new InvalidRadiusException(newRadius); } public static int getNumberOfObjects() { return numberOfObjects; } }

public class Main { public static void main(String[] args) { try { Circle c1 = new Circle(5); c1.setRadius(-5); Circle c2 = new Circle(0); } catch (InvalidRadiusException ex) { System.out.println(“Invalid Radius: ” + ex.getRadius()); } System.out.println("Number of objects created: " + Circle.getNumberOfObjects()); } Output: Invalid radius: -5.0 Number of objects created: 1

When to create Custom Exception classes Use the exception classes in the API whenever possible. You should write your own exception classes if you answer ‘yes’ to one of the following: Do you need an exception type that isn't represented by those in the Java platform? Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors? Do you want to pass more than just a string to the exception handler?

When to Use Exceptions Use it if the event is truly exceptional and is an error Do not use it to deal with simple, expected situations. Example: 31 try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null"); } Can be replaced by: if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null");

Get more info! Java docs: Exception Sun Tutorial on Exception Handling Exception