1. 2 Examples for Exception?... An exception is an abnormal condition that arises in a code sequence at run time (Run time error). In other computer languages.

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
Index Exception handling Exception In Java Exception Types
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
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.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
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.
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.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
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.
Object Oriented Programming with Java (150704).  Throwable Exception (This class will catch exceptions generated by prog.) (Create your own custom exception.
Slides Credit Umair Javed LUMS Web Application Development.
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:
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
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.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
© Mohamed Nuzrath Java Programming :: Chapter 6 :: Prepared & Presented By :: Mohamed Nuzrath [ Major In Programming ] NCC Programme coordinator IT Lecturer.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
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.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
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.
COP 3330 Notes 3/7. Today’s Topics Exceptions Abstract Classes.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
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.
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.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
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
COMPSCI 230 S Programming Techniques
Handling Exceptions.
Advanced Programming Behnam Hatami Fall 2017.
Chapter 12 Exception Handling and Text IO
TRY CATCH BLOCK By Kosala Rajapaksha.
Web Design & Development Lecture 7
Exception Handling in Java
Managing Errors and Exceptions
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.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Basics Exception Handling.
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:

1

2 Examples for Exception?... An exception is an abnormal condition that arises in a code sequence at run time (Run time error). In other computer languages that do not support exception handling, errors must be checked and handled manually. - Through the error codes But java brings run time error management in to the object oriented world.

3 Example 1:... class Example1_Exceptions { public static void main(String arg[]) { int arr[]={3,5,6,9,10}; for(int i=0;i<6;i++) { System.out.println(arr[i]); } class Example1_Exceptions { public static void main(String arg[]) { int arr[]={3,5,6,9,10}; for(int i=0;i<6;i++) { System.out.println(arr[i]); } java.lang.ArrayIndexOutOfBoundsException

4 Example 2 :... class Student { int age; String name; } class Example2_Exceptions { public static void main(String arg[]) { Student s[]=new Student[5]; s[0].age=21; s[0].name="Kamal“; } class Student { int age; String name; } class Example2_Exceptions { public static void main(String arg[]) { Student s[]=new Student[5]; s[0].age=21; s[0].name="Kamal“; } java.lang.NullPointerException

5 Example 3 :... class Example3_Exceptions { public static void main(String arg[]) { int a=0; float avg=56/a; System.out.println(avg); } class Example3_Exceptions { public static void main(String arg[]) { int a=0; float avg=56/a; System.out.println(avg); } java.lang.ArithmeticException: / by zero

04/30/106 Example 4 :... class Example3_Exceptions { public static void main(String arg[]) { String weight="34kg"; double w=Double.parseDouble(weight); System.out.println(w); } class Example3_Exceptions { public static void main(String arg[]) { String weight="34kg"; double w=Double.parseDouble(weight); System.out.println(w); } Exception in thread "main" java.lang.NumberFormatException: For input string: "34kg“ at sun.misc.FloatingDecimal.readJavaFormatString( FloatingDecimal.java:1224) at java.lang.Double.parseDouble(Double.java:510) at ExceptionHandling.main(ExceptionHandling.java:12)

7 Exception Hierarchy... Java.lang.Throwable J ava.lang.Exception Java.lang.Error Java.lang.RuntimeException Java.lang.IOException

8 How java handles the exceptions ?... When the java run time system detects a run time error in the program, it constructs a new exception object and then throws this exception. This causes the execution of the program to stop at the point of detecting the error. Because once an exception has been thrown, it catches by an exception handler and deals with it immediately. This default handler is provided by the java runtime system. These exceptions are called as uncaught exceptions. The default handler displays a String describing the exception specifying the point at which the exception occurred. Then terminates the program.

9 Managing Exceptions... Managing exceptions within the code itself is very important, although the default handler manages the exceptions into some extent. 1.It allows to fix the error 2.It prevents the program from automatically terminating. Java Exceptions are managed via Five keywords. I.try II.catch III.finally IV.throw V.throws

10 Using try and catch... To handle a runtime error, simply enclose the code that wants to monitor, inside a try block. Immediately following the try block, include a catch clause that specifies the exception type that wishes to catch. try { //Code to monitor an error } catch(Exception_Type object_of_the_instance) { //Task to do when an exception is found } try { //Code to monitor an error } catch(Exception_Type object_of_the_instance) { //Task to do when an exception is found }

04/30/1011 try-catch Example (1):... class Example_Exceptions { public static void main(String arg[]) { try { int a=0; float avg=56/a; System.out.println(avg); } catch(ArithmeticException err) { System.out.println(“Devides by zero”); } class Example_Exceptions { public static void main(String arg[]) { try { int a=0; float avg=56/a; System.out.println(avg); } catch(ArithmeticException err) { System.out.println(“Devides by zero”); }

12 Using try and catch (cont)... Once an exception is thrown, program control transfers out of the try block into the catch block. Execution never returns to the try block from a catch. Once the catch statement has executed, program control continues with the next line in the program following the entire try-catch block. To print the error message as it’s original format, catch(Exception err) { System.out.println(err.toString()); }

04/30/1013 try-catch Example (2):... Import java.util.Random; class Example_Exceptions { public static void main(String arg[]) { try { Random r=new Random(); int b=r.nextInt(); int c=r.nextInt(); int a=b/c; System.out.println(“b: ”+b+”\nc: ”+c+”\na:”+a); } catch(ArithmeticException e) { System.out.println(“Divides by zero”); } Import java.util.Random; class Example_Exceptions { public static void main(String arg[]) { try { Random r=new Random(); int b=r.nextInt(); int c=r.nextInt(); int a=b/c; System.out.println(“b: ”+b+”\nc: ”+c+”\na:”+a); } catch(ArithmeticException e) { System.out.println(“Divides by zero”); }

04/30/1014 Using try, catch and finally... Suppose there is an action that absolutely must do, regardless of an exception is thrown or not. In such cases, the finally clause is essential. try { //Code to monitor an error } catch(Exception_Type object_of_the_instance) { //Task to do when an exception is found } finally { //The task to do regardless of exception occurs or not } try { //Code to monitor an error } catch(Exception_Type object_of_the_instance) { //Task to do when an exception is found } finally { //The task to do regardless of exception occurs or not }

15 Using try and finally... It is possible to use only the try and finally clauses without using catch clause. try { //Code to monitor an error } finally { //The task to do regardless of exception occurs or not } try { //Code to monitor an error } finally { //The task to do regardless of exception occurs or not }

04/30/1016 try, catch and finally-Example(1)... Reading a text file. try { //Open the text file //Read the text file IOException may occur when reading the text file //Close the text file } catch(IOException err) { //Task to do when an exception is found } finally { //Close the text file } try { //Open the text file //Read the text file IOException may occur when reading the text file //Close the text file } catch(IOException err) { //Task to do when an exception is found } finally { //Close the text file }

17 Using throws... If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. class Checked_Exceptions { ( method signature) throws Exception_Type { //The code that will cause to a checked exception } class Checked_Exceptions { ( method signature) throws Exception_Type { //The code that will cause to a checked exception }

18 throws Example... class Checked_Exceptions { public static void main(String args[]) throws IOException { //open the file to read //Read the file //Close the file } class Checked_Exceptions { public static void main(String args[]) throws IOException { //open the file to read //Read the file //Close the file }

19 Using throws (cont)... A method may return more than one exception, in which case the exceptions are declared in a list separated by commas. class Checked_Exceptions { ( method signature) throws Exception1, Exception2…….. { //The code that will cause to a checked exception } class Checked_Exceptions { ( method signature) throws Exception1, Exception2…….. { //The code that will cause to a checked exception }

20 Using throw... Class Throw_Exceptions { ( method signature) { try { throw new NullPointerException(“Exception occurred”); } catch(NullPointerException err) { System.out.println(err.toString ()); } Class Throw_Exceptions { ( method signature) { try { throw new NullPointerException(“Exception occurred”); } catch(NullPointerException err) { System.out.println(err.toString ()); }

21 NOTE on Exceptions... DO NOT USE EXCEPTION HANDLING, If the exception could be handled easily with a simple expression. Ex: ArrayIndexOutOfBoundsException could easily handled using correct length of the array. ArithmeticExceptions like divide by zero, could be handled using simple if-else statements. if(a==0) { }

22 NOTE on Exceptions (cont)... Exceptions take up a lot of processing time for the java program. a simple test or series of tests will run much faster than exception handling and make the java program more efficient. EXCEPTIONS SHOULD BE USED ONLY FOR TRULY EXCEPTIONAL CASES THAT ARE OUT OF CONTROL. EXCEPTIONS SHOULD BE USED ONLY FOR TRULY EXCEPTIONAL CASES THAT ARE OUT OF CONTROL.