2- Runtime exception: UnChecked (execution of program) automatically propagated in java. don t have to throw, you can but isn t necessary

Size: px
Start display at page:

Download "2- Runtime exception: UnChecked (execution of program) automatically propagated in java. don t have to throw, you can but isn t necessary"

Transcription

1 EXCEPTIONS categories of exceptions: Checked exception: thrown at the time of compilation Runtime exception: UnChecked (execution of program) automatically propagated in java. don t have to throw, you can but isn t necessary Errors: UnChecked = not exceptions at all, but problems that arise beyond the control of the user or the programmer automatically propagated in java. indicate that something severe enough has gone wrong, the application should crash rather than try to handle the error Checked Exceptions Why this compilation error? How to resolve the error?...5 Checked Exception Example...5 Method 1: Declare the exception using throws keyword....6 Method 2: Handle them using try-catch blocks Unchecked RuntimeException, ie built-in Exceptions How to resolve the error?...8 Unchecked Exception Example...8 Class: Java.lang.NullPointerException) Unchecked RuntimeException...9 Class: Java.lang.ArithmeticException Unchecked RuntimeException...9 Class: Java.lang.ArrayIndexOutOfBoundsException Unchecked RuntimeException Class: Java.lang.NumberFormatException Unchecked RuntimeException Class: Java.lang.StringIndexOutOfBoundsException Unchecked RuntimeException Error which is unchecked too Exceptions Methods What is the difference between Throw and Throws in Java Exception Handling? Throw Example The catch block will handle the Exception What is Exception Propagation? What is the need of having throws keyword when you can handle exception using try-catch? What is Exception Handling? Explain the exception hierarchy in Java? What is the difference between error and exception? What is Exception Handling? Explain the exception hierarchy in Java? What is the difference between Checked Exception and Unchecked Exception? What is the difference between error and exception? When is custom exception class needed? How to create a custom exception class? Is it necessary that each try block must be followed by a catch block? Are you aware of any scenario when finally will not be executed? What is a nested try statement?

2 19. What are multiple catch blocks? What is exception propagation? What is throw keyword? What is throws clause? Difference between throw and throws? final Vs finally Vs finalize What are the two rules of exception handling with respect to method overriding? What is the error in the following code? What is multi-catch statement in Java 7? What is try-with-resources or ARM in Java 7? When is custom exception class needed? How to create a custom exception class? Is it necessary that each try block must be followed by a catch block? Are you aware of any scenario when finally will not be executed? What is a nested try statement? What are multiple catch blocks? What is exception propagation? What is throw keyword? final Vs finally Vs finalize What are the two rules of exception handling with respect to method overriding? What is the error in the following code? What is multi-catch statement in Java 7? What is try-with-resources or ARM in Java 7? How to Catch an Exceptions: Example: How to use Multiple catch Blocks: Example: How to Create an Exception Class How to declare you own Exception: Example: Question: Is the following code legal? Question: What exception types can be caught by the following handler? What is wrong with using this type of exception handler? Question: Is there anything wrong with this exception handler as written? Will this code compile? Question: Match each situation in the first list with an item in the second list Exercise: Modify the following cat method so that it will compile: needed catch to go with finally, finally needed logic best is add try and catch Embedding information in an exception object Threads and Exceptions

3 Exceptions object that wraps an error event that occurred within a method and contains Information about the error including its type, state, optional information 3 categories of exceptions: 1- Checked exception: thrown at the time of compilation. Should be wrapped in a try-catch block or specified as throws clause must throw exception by using throws keyword. and manually propagate them. 2- Runtime exception: UnChecked (execution of program) automatically propagated in java. don t have to throw, you can but isn t necessary 3- Errors: UnChecked = not exceptions at all, but problems that arise beyond the control of the user or the programmer automatically propagated in java. indicate that something severe enough has gone wrong, the application should crash rather than try to handle the error. 3

4 Un-Checked Checked = Compile Time Un-Checked Run-time throws IOException is a parent class so auto covers chilildren too Option 1 Try-Catch (exception x) Manually Propagate catch(exception e) log(e); throw(e); Option 2 Required Any checked that can happen must throws method Throws EOFException FileNotFoundException ClassNotFoundException CloneNotSupportedException IllegalAccessException InstantiationException InterruptedException NoSuchFieldException NoSuchMethodException ArithmeticException ArrayIndexOutOfBoundsException ArrayStoreException ClassCastException IllegalArgumentException IllegalMonitorStateException IllegalStateException IllegalThreadStateException IndexOutOfBoundsException NegativeArraySizeException NullPointerException NumberFormatException SecurityException StringIndexOutOfBounds UnsupportedOperationException Option 1 Try-Catch (exception x) Manually Propagate Option 2 method Throws EOFException Not auto prop Throw compilation error Auto Propagate 4

5 1 - Checked Exceptions Exception Exception IOException FileNotFoundException ClassNotFoundException CloneNotSupportedException IllegalAccessException InstantiationException InterruptedException NoSuchFieldException NoSuchMethodException Description Class not found. Attempt to clone an object that does not implement the Cloneable interface. Access to a class is denied. Attempt to create an object of an abstract class or interface. One thread has been interrupted by another thread. A requested field does not exist. A requested method does not exist. 1. Why this compilation error? checked exceptions gets checked during compile time. Since we didn t handled/declared the exceptions, our program gave the compilation error. 2. How to resolve the error? 1. method throws someexception auto catches 2. try something catch(filenotfoundexception fnfe) best to use, more meaningful Checked Exception Example In this example we are reading the file myfile.txt and displaying its content on the screen. In this program there are three places where a checked exception is thrown as mentioned in the comments below. FileInputStream which is used for specifying the file path and name, throws FileNotFoundException. The read() method which reads the file content throws IOException and the close() method which closes the file input stream also throws IOException. import java.io.*; class Example public static void main(string args[]) FileInputStream fis = null; 5 // This constructor FileInputStream(File filename) // throws a checked exception: FileNotFoundException fis = new FileInputStream("B:/myfile.txt"); int k; // Method read() of FileInputStream class also // throws a checked exception: IOException while(( k = fis.read() )!= -1) System.out.print((char)k);

6 Output: // The method close() closes the file input stream // throws a checked exception: IOException*/ fis.close(); Exception in thread "main" java.lang.error: Unresolved compilation problems: Unhandled exception type FileNotFoundException Unhandled exception type IOException Unhandled exception type IOException Method 1: Declare the exception using throws keyword. As we know that all three occurrences of checked exceptions are inside main() method so one way to avoid the compilation error is: Declare the exception in the method using throws keyword. You may be thinking that our code is throwing FileNotFoundException and IOException both then why we are declaring the IOException alone. The reason is that IOException is a parent class of FileNotFoundException so it by default covers that. import java.io.*; class Example OR public static void main(string args[]) throws IOException, FileNotFoundException. public static void main(string args[]) throws IOException FileInputStream fis = null; fis = new FileInputStream("B:/myfile.txt"); int k; Output: while(( k = fis.read() )!= -1) System.out.print((char)k); fis.close(); File content is displayed on the screen. 6

7 Method 2: Handle them using try-catch blocks. The approach we have used above is not good at all. It is not the best exception handling practice. You should give meaningful message for each exception type so that it would be easy for someone to understand the error. The code should be like this: import java.io.*; class Example public static void main(string args[]) FileInputStream fis = null; try fis = new FileInputStream("B:/myfile.txt"); catch(filenotfoundexception fnfe) System.out.println("The specified file is not present"); int k; try while(( k = fis.read() )!= -1) System.out.print((char)k); fis.close(); catch(ioexception ioe) System.out.println("I/O error occurred: "+ioe); This code will run fine and will display the file content. Checked exception: must throw exception by using throws keyword. and manually propagate them. public class ExceptionTest public static void main(string[] args)throws FileNotFoundException method1(); System.out.println("after calling m()"); static void method1() throws FileNotFoundException method2(); static void method2() throws FileNotFoundException method3(); static void method3() throws FileNotFoundException throw new FileNotFoundException(); 7

8 2 - Unchecked RuntimeException, ie built-in Exceptions Exception ArithmeticException ArrayIndexOutOfBoundsException ArrayStoreException ClassCastException IllegalArgumentException IllegalMonitorStateException IllegalStateException IllegalThreadStateException IndexOutOfBoundsException NegativeArraySizeException NullPointerException NumberFormatException SecurityException StringIndexOutOfBounds UnsupportedOperationException Description Arithmetic error, such as divide-by-zero. Array index is out-of-bounds. Assignment to an array element of an incompatible type. Invalid cast. Illegal argument used to invoke a method. Illegal monitor operation, such as waiting on an unlocked thread. Environment or application is in incorrect state. Requested operation not compatible with current thread state. Some type of index is out-of-bounds. Array created with a negative size. Invalid use of a null reference. Invalid conversion of a string to a numeric format. Attempt to violate security. Attempt to index outside the bounds of a string. An unsupported operation was encountered. 3. How to resolve the error? 1. try something catch(filenotfoundexception fnfe) Unchecked Exception Example class Example public static void main(string args[]) int num1=10; int num2=0; //Since I'm dividing an integer with 0 //it should throw ArithmeticException int res=num1/num2; System.out.println(res); If you compile this code, it would compile successfully however when you will run it, it would throw ArithmeticException. That clearly shows that unchecked exceptions are not checked at compile-time, they occurs at runtime. Lets see another example. class Example public static void main(string args[]) int arr[] =1,2,3,4,5; // My array has only 5 elements but we are trying to // display the value of 8th element. It should throw // ArrayIndexOutOfBoundsException 8

9 System.out.println(arr[7]); This code would also compile successfully since ArrayIndexOutOfBoundsException is also an unchecked exception. Note: It doesn t mean that compiler is not checking these exceptions so we shouldn t handle them. In fact we should handle them more carefully. For e.g. In the above example there should be a exception message to user that they are trying to display a value which doesn t exist in array so that user would be able to correct the issue. class Example public static void main(string args[]) try int arr[] =1,2,3,4,5; System.out.println(arr[7]); catch(arrayindexoutofboundsexception e) System.out.println("The specified index does not exist " + "in array. Please correct the error."); Output: The specified index does not exist in array. Please correct the error. Class: Java.lang.NullPointerException) Unchecked RuntimeException public class ExceptionTest public static void main(string[] args) method1(); System.out.println("after calling m()"); static void method1() method2(); static void method2() method3(); static void method3() OR throw new NullPointerException ("some text"); throw new NullPointerException(e); //throw is followed by instance variable Class: Java.lang.ArithmeticException Unchecked RuntimeException This is a built-in-class present in java.lang package. This exception occurs when an integer is divided by zero. class Example1 public static void main(string args[]) 9

10 try int num1=30, num2=0; int output=num1/num2; System.out.println ("Result: "+output); catch(arithmeticexception e) System.out.println ("You Shouldn't divide a number by zero"); Output of above program: You Shouldn't divide a number by zero Class: Java.lang.ArrayIndexOutOfBoundsException Unchecked RuntimeException class ExceptionDemo2 public static void main(string args[]) try int a[]=new int[10]; //Array has only 10 elements a[11] = 9; catch(arrayindexoutofboundsexception e) System.out.println ("ArrayIndexOutOfBounds"); Output: ArrayIndexOutOfBounds Class: Java.lang.NumberFormatException Unchecked RuntimeException This exception occurs when a string is parsed to any numeric variable. For example, the statement int num=integer.parseint ("XYZ"); would throw NumberFormatExceptionbecause String XYZ cannot be parsed to int. class ExceptionDemo3 public static void main(string args[]) try int num=integer.parseint ("XYZ") ; System.out.println(num); catch(numberformatexception e) System.out.println("Number format exception occurred"); Output: Number format exception occurre Class: Java.lang.StringIndexOutOfBoundsException Unchecked RuntimeException An object of this class gets created whenever an index is invoked of a string, which is not in the range. class ExceptionDemo4 public static void main(string args[]) try 10 String str="beginnersbook";

11 System.out.println(str.length());; char c = str.charat(0); c = str.charat(40); System.out.println(c); catch(stringindexoutofboundsexception e) System.out.println("StringIndexOutOfBoundsException!!"); Output: 13 StringIndexOutOfBoundsException!! 11

12 3 - Error which is unchecked too Exception Description AssertionError ExceptionInInitializerError StackOverflowError NoClassDefFoundError java.util: 1. ConcurrentModificationException java.io : 1. EOFException 2. FileNotFoundException 3. IOException 4. NotSerializableException Exceptions Methods Following is the list of important methods available in the Throwable class. Sr.No Method & Description public String getmessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. public Throwable getcause() Returns the cause of the exception as represented by a Throwable object. public String tostring() Returns the name of the class concatenated with the result of getmessage(). public void printstacktrace() Prints the result of tostring() along with the stack trace to System.err, the error output stream. public StackTraceElement [] getstacktrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. public Throwable fillinstacktrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace

13 4. What is the difference between Throw and Throws in Java Exception Handling? Throw: 1. throw an exception explicitly. 2. throw is followed by instance variable 3. used inside method body to invoke an exception 4. cannot throw more than one exception 5. does not terminate program throw new ArithmeticException("Arithmetic Exception"); Throws: 1. throws will pass the error to its caller 2. used to declare an exception. 3. followed by exception class names. 4. used in method declaration (signature). 5. declare multiple exceptions private static void throwsmethod() throws ArithmeticException; Throw Example public class Example1 void checkage(int age) if(age<18) throw new ArithmeticException("Not Eligible for voting"); else System.out.println("Eligible for voting"); public static void main(string args[]) Example1 obj = new Example1(); obj.checkage(13); System.out.println("End Of Program"); Output: Exception in thread "main" java.lang.arithmeticexception: Not Eligible for voting at Example1.checkAge(Example1.java:4) at Example1.main(Example1.java:10) 13

14 5. The catch block will handle the Exception If you execute the following example, you will know the difference between a Throw and a Catch block. In general terms: 1. The catch block will handle the Exception 2. throws will pass the error to his caller. In the following example, the error occurs in the throwsmethod() but it is handled in the catchmethod(). public class CatchThrow private static void throwsmethod() throws NumberFormatException String intnumber = "5A"; Integer.parseInt(intNumber); private static void catchmethod() try throwsmethod(); catch (NumberFormatException e) System.out.println("Convertion Error"); public static void main(string[] args) // TODO Auto-generated method stub catchmethod(); Try/catch and throw clause are for different purposes. So they are not alternative to each other but they are complementary. 1. If you have throw some checked exception in your code, it should be inside some try/catch in codes calling hierarchy. 2. Conversely, you need try/catch block only if there is some throw clause inside the code (your code or the API call) that throws checked exception. Sometimes, you may want to throw exception if particular condition occurred which you want to handle in calling code block and in some cases handle some exception catch block and throw a same or different exception again to handle in calling block. All these keywords try, catch and throw are related to the exception handling concept in java. An exception is an event that occurs during the execution of programs. Exception disrupts the normal flow of an application. Exception handling is a mechanism used to handle the exception so that the normal flow of application can be maintained. Try-catch block is used to handle the exception. In a try block, we write the code which may throw an exception and in catch block we write code to handle that exception. Throw keyword is used to explicitly throw an exception. Generally, throw keyword is used to throw user defined exceptions. 14

15 6. What is Exception Propagation? After a method throws an exception, the runtime system searches the call stack for a method that contains a block of code(exception handler) that can handle the exception. 7. What is the need of having throws keyword when you can handle exception using try-catch? Well, thats a valid question. We already know we can handle exceptions using try-catch block. The throws does the same thing that try-catch does but there are some cases where you would prefer throws over try-catch. For example: Lets say we have a method mymethod() that has statements that can throw either ArithmeticException or NullPointerException, in this case you can use try-catch as shown below: public void mymethod() try // Statements that might throw an exception catch (ArithmeticException e) // Exception handling statements catch (NullPointerException e) // Exception handling statements But suppose you have several such methods that can cause exceptions, in that case it would be tedious to write these try-catch for each method. The code will become unnecessary long and will be less-readable. One way to overcome this problem is by using throws like this: declare the exceptions in the method signature using throws and handle the exceptions where you are calling this method by using try-catch. Another advantage of using this approach is that you will be forced to handle the exception when you call this method, all the exceptions that are declared using throws, must be handled where you are calling this method else you will get compilation error. public void mymethod() throws ArithmeticException, NullPointerException // Statements that might throw an exception public static void main(string args[]) try mymethod(); catch (ArithmeticException e) // Exception handling statements catch (NullPointerException e) // Exception handling statements 8. What is Exception Handling? Five keywords used to manage Java exception handling try - Any code that might throw an exception is enclosed within a try block. catch - If an exception occurs in try block, catch block can provide exception handlers to handle it in a rational manner. 15

16 16 finally - The finally block always executes when the try block exits. So, any code that must execute after a try block is completed should be put in finally block. throw - throw is used to manually thrown an exception. throws - Any exception that is thrown in a method but not handled there must be specified in a throws clause. 9. Explain the exception hierarchy in Java? Throwable class is the super class of all the exception types. Below Throwable class there are two subclasses which denotes two distinct branches of exceptions - Exception - An Exception indicates that a problem has occurred, but it is not a serious system problem. The user programs you write will throw and catch Exceptions. Error - It defines exceptions that are not expected to be caught by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Examples of error are StackOverflowError, OutOfMemoryError etc. 10. What is the difference between error and exception? Exception - An Exception indicates that a problem has occurred, but it is not a serious system problem. The user programs you write will throw and catch Exceptions. Error - It defines exceptions that are not expected to be caught by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Examples of error are StackOverflowError, OutOfMemoryError etc. Java Exception Handling interview questions 11. What is Exception Handling? Exception Handling in Java provides a way to handle a situation when an exception is thrown and shows a meaningful message to the user and continue with the flow of the program. When an exceptional condition occurs with in a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred. The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception. Five keywords used to manage Java exception handling try - Any code that might throw an exception is enclosed within a try block. catch - If an exception occurs in try block, catch block can provide exception handlers to handle it in a rational manner. finally - The finally block always executes when the try block exits. So, any code that must execute after a try block is completed should be put in finally block. throw - throw is used to manually thrown an exception. throws - Any exception that is thrown in a method but not handled there must be specified in a throws clause. 12. Explain the exception hierarchy in Java? Throwable class is the super class of all the exception types. Below Throwable class there are two subclasses which denotes two distinct branches of exceptions -

17 Exception - An Exception indicates that a problem has occurred, but it is not a serious system problem. The user programs you write will throw and catch Exceptions. Error - It defines exceptions that are not expected to be caught by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Examples of error are StackOverflowError, OutOfMemoryError etc. 13. What is the difference between Checked Exception and Unchecked Exception? Checked Exception is a direct subclass of Exception. should be wrapped in a try-catch block or specified as throws clause where as there is no such requirement for unchecked exception. Failure to provide exception handling mechanism for checked exception result in compiler error designed to reduce the number of exceptions which are not properly handled and where there is a reasonable chance for recovery. UnCheckedExceptions are mostly programming errors UnChecked exception a subclass of RunTimeException no compile time error for unchecked exception. 14. What is the difference between error and exception? Exception - An Exception indicates that a problem has occurred, but it is not a serious system problem. The user programs you write will throw and catch Exceptions. Error - It defines exceptions that are not expected to be caught by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Examples of error are StackOverflowError, OutOfMemoryError etc. 15. When is custom exception class needed? How to create a custom exception class? According to Java Docs, you should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's. 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? Does your code throw more than one related exception? If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained? 16. Is it necessary that each try block must be followed by a catch block? No it is not mandatory that there should be a catch block after a try block. try block can have only a matching finally block. So there are these valid combnations try-catch-finally, try-catch, try-finally. 17. Are you aware of any scenario when finally will not be executed? According to Java docs. If the JVM exits (By explicitly using System.exit() or a JVM crash) while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues. 17

18 18. What is a nested try statement? 18 A try-catch-finally block can reside inside another try-catch-finally block that is known as nested try statement. public class NestedTryDemo public static void main(string[] args) try System.out.println("In Outer try block"); try System.out.println("In Inner try block"); int a = 7 / 0; catch (IllegalArgumentException e) System.out.println("IllegalArgumentException caught"); finally System.out.println("In Inner finally"); catch (ArithmeticException e) System.out.println("ArithmeticException caught"); finally System.out.println("In Outer finally"); 19. What are multiple catch blocks? There might be a case when a code enclosed with in a try block throws more than one exception. To handle these types of situations, two or more catch clauses can be specified where each catch clause catches a different type of exception. When an exception is thrown, each of the catch statement is inspected in order, and the first one whose type matches that of the thrown exception is executed. int a[] = 0; try int b = 7/a[i]; catch(arithmeticexception aexp) aexp.printstacktrace(); catch(arrayindexoutofboundsexception aiexp) aiexp.printstacktrace(); 20. What is exception propagation? When an exceptional condition occurs within a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred. The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception. If your program is not able to catch any particular exception, that will ultimately be processed by the default handler. This process of going through the method stack is known as Exception propagation. 21. What is throw keyword? It is possible for a Java program to throw an exception explicitly that is done using the throw statement. The general form of throw is - throw throwableobject; We can get this throwableobject in 2 ways - By using the Exception parameter of catch block. Create a new one using the new operator.

19 19 try throw new NullPointerException(); catch(nullpointerexception nexp) System.out.println("Exception caught in catch block of displayvalue"); throw nexp; 22. What is throws clause? If in a method we don't want to handle any exception but want to leave it to the calling method to handle any exception that is thrown by the called method, it is done using throws keyword. Using throws a method can just declare the exception it may throw and callers of the method have to provide exception handling for those exceptions (or they can also declare them using throws). General form of a method declaration that includes a throws clause type method-name(parameter-list) throws exception-list // body of method Here, exception-list is a comma-separated list of the exceptions that a method can throw. 23. Difference between throw and throws? throw is used to throw an exception. throws is used to declare an exception, in the method signature, that can be thrown from a method. 24. final Vs finally Vs finalize final - final keyword is used to restrict in some way. It can be used with variables, methods and classes. When a variable is declared as final, its value can not be changed once it is initialized. Except in case of blank final variable, which must be initialized in the CONSTRUCTOR. If you make a method final in Java, that method can't be overridden in a sub class. If a class is declared as final then it can not be sub classed. finally - finally is part of exception handling mechanism in Java. finally block is used with try-catch block. finally block is always executed whether any exception is thrown or not and raised exception is handled in catch block or not. Since finally block always executes thus it is primarily used to close the opened resources like database connection, file handles etc. finalize() - finalize() method is a protected method of java.lang.object class. Since it is in Object class thus it is inherited by every class. This method is called by garbage collector thread before removing an object from the memory. This method can be overridden by a class to provide any cleanup operation and gives object final chance to cleanup before getting garbage collected. protected void finalize() throws Throwable //resource clean up operations 25. What are the two rules of exception handling with respect to method overriding? If superclass method has not declared any exception using throws clause then subclass overridden method can't declare any checked exception though it can declare unchecked exception. If superclass method has declared an exception using throws clause then subclass overridden method can do one of the three things. sub-class can declare the same exception as declared in the super-class method. subclass can declare the subtype exception of the exception declared in the superclass method. But subclass method can not declare any exception that is up in the hierarchy than the exception declared in the super class method.

20 subclass method can choose not to declare any exception at all. 26. What is the error in the following code? class Parent public void displaymsg() throws IOException System.out.println("In Parent displaymsg()"); throw new IOException("Problem in method - displaymsg - Parent"); public class ExceptionOverrideDemo extends Parent public void displaymsg() throws Exception System.out.println("In ExceptionOverrideDemo displaymsg()"); throw new Exception("Problem in method - displaymsg - ExceptionOverrideDemo"); Here parent class had declared IOException where as subclass has declared Exception. Exception is the super class of IOException thus it is wrong according to the rules of method overriding and exception handling. Thus the code will give compiler error. 27. What is multi-catch statement in Java 7? Before Java 7 multi-catch statement, if two or more exceptions were handled in the same way, we still had to write separate catch blocks for handling them. catch(ioexception exp) logger.error(exp); throw exp; catch(sqlexception exp) logger.error(exp); throw exp; With Java 7 and later it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code. Each exception type within the multi-catch statement is separated by Pipe symbol ( ). catch(ioexception SQLException exp) logger.error(exp); throw exp; 28. What is try-with-resources or ARM in Java 7? Java 7 introduced a new form of try known as try-with-resources for Automatic Resource Management (ARM). Here resource is an object that must be closed after the program is finished with it. Example of resources would be an opened file handle or database connection etc. Before the introduction of try-with-resources we had to explicitly close the resources once the try block completes normally or abruptly. try br = new BufferedReader(new FileReader("C:\\test.txt")); System.out.println(br.readLine()); catch (IOException e) e.printstacktrace(); finally try if (br!= null) System.out.println("Closing the file"); br.close(); catch (IOException ex) 20

21 ex.printstacktrace(); try-with-resources helps in reducing such boiler plate code. Let's see the same example using try-withresources. try(bufferedreader br = new BufferedReader(new FileReader("C:\\test.txt"))) System.out.println(br.readLine()); catch (IOException e) e.printstacktrace(); 29. When is custom exception class needed? How to create a custom exception class? 21 According to Java Docs, you should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's. 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? 30. Is it necessary that each try block must be followed by a catch block? No it is not mandatory that there should be a catch block after a try block. try block can have only a matching finally block. So there are these valid combnations try-catch-finally, try-catch, try-finally. 31. Are you aware of any scenario when finally will not be executed? According to Java docs. If the JVM exits (By explicitly using System.exit() or a JVM crash) while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues. 32. What is a nested try statement? A try-catch-finally block can reside inside another try-catch-finally block that is known as nested try statement. public class NestedTryDemo public static void main(string[] args) try System.out.println("In Outer try block"); try System.out.println("In Inner try block"); int a = 7 / 0; catch (IllegalArgumentException e) System.out.println("IllegalArgumentException caught"); finally System.out.println("In Inner finally"); catch (ArithmeticException e) System.out.println("ArithmeticException caught"); finally System.out.println("In Outer finally");

22 33. What are multiple catch blocks? There might be a case when a code enclosed with in a try block throws more than one exception. To handle these types of situations, two or more catch clauses can be specified where each catch clause catches a different type of exception. When an exception is thrown, each of the catch statement is inspected in order, and the first one whose type matches that of the thrown exception is executed. int a[] = 0; try int b = 7/a[i]; catch(arithmeticexception aexp) aexp.printstacktrace(); catch(arrayindexoutofboundsexception aiexp) aiexp.printstacktrace(); 34. What is exception propagation? When an exceptional condition occurs within a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred. The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception. If your program is not able to catch any particular exception, that will ultimately be processed by the default handler. This process of going through the method stack is known as Exception propagation. 35. What is throw keyword? throw an exception explicitly that is done using the throw statement. We can get this throwableobject in 2 ways - 1- Create a new one using the new operator. OR 2- By using the Exception parameter of catch block. try throw new NullPointerException(); //get as propagated up catch(nullpointerexception nexp) System.out.println("Exception caught in catch block of displayvalue"); throw nexp; 22

23 36. Unchecked exceptions auto prop, checked exceptions must throw exception by using throws Whenever methods are called stack is formed and an exception is first thrown from the top of the stack and if it is not caught, it starts coming down the stack to previous methods until it is not caught. If exception remains uncaught even after reaching bottom of the stack it is propagated to JVM and program is terminated. unchecked exceptions are automatically propagated in java. Program > public class ExceptionTest public static void main(string[] args) method1(); System.out.println("after calling m()"); static void method1() method2(); static void method2() method3(); static void method3() throw new NullPointerException(); For propagating checked exceptions method must throw exception by using throws keyword. Program > public class ExceptionTest public static void main(string[] args) throws FileNotFoundException method1(); System.out.println("after calling m()"); static void method1() throws FileNotFoundException method2(); static void method2() throws FileNotFoundException method3(); static void method3() throws FileNotFoundException throw new FileNotFoundException(); 23

24 Propagating unchecked exception (NullPointerException) > Propagating checked exception (FileNotFoundException) using throws keyword > 24

25 37. final Vs finally Vs finalize final - final keyword is used to restrict in some way. It can be used with variables, methods and classes. When a variable is declared as final, its value can not be changed once it is initialized. Except in case of blank final variable, which must be initialized in the CONSTRUCTOR. If you make a method final in Java, that method can't be overridden in a sub class. If a class is declared as final then it can not be sub classed. finally - finally is part of exception handling mechanism in Java. finally block is used with try-catch block. finally block is always executed whether any exception is thrown or not and raised exception is handled in catch block or not. Since finally block always executes thus it is primarily used to close the opened resources like database connection, file handles etc. finalize() - finalize() method is a protected method of java.lang.object class. Since it is in Object class thus it is inherited by every class. This method is called by garbage collector thread before removing an object from the memory. This method can be overridden by a class to provide any cleanup operation and gives object final chance to cleanup before getting garbage collected. protected void finalize() throws Throwable //resource clean up operations 38. What are the two rules of exception handling with respect to method overriding? If superclass method has not declared any exception using throws clause then subclass overridden method can't declare any checked exception though it can declare unchecked exception. If superclass method has declared an exception using throws clause then subclass overridden method can do one of the three things. sub-class can declare the same exception as declared in the super-class method. subclass can declare the subtype exception of the exception declared in the superclass method. But subclass method can not declare any exception that is up in the hierarchy than the exception declared in the super class method. subclass method can choose not to declare any exception at all. 39. What is the error in the following code? class Parent public void displaymsg() throws IOException System.out.println("In Parent displaymsg()"); throw new IOException("Problem in method - displaymsg - Parent"); public class ExceptionOverrideDemo extends Parent public void displaymsg() throws Exception System.out.println("In ExceptionOverrideDemo displaymsg()"); throw new Exception("Problem in method - displaymsg - ExceptionOverrideDemo"); parent class had declared IOException where as subclass has declared Exception. Exception is the super class of IOException thus it is wrong according to the rules of method overriding and exception handling. Thus the code will give compiler error. 25

26 40. What is multi-catch statement in Java 7? Before Java 7 multi-catch statement, if two or more exceptions were handled in the same way, we still had to write separate catch blocks for handling them. catch(ioexception exp) logger.error(exp); throw exp; catch(sqlexception exp) logger.error(exp); throw exp; With Java 7 and later it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code. Each exception type within the multi-catch statement is separated by Pipe symbol ( ). catch(ioexception SQLException exp) logger.error(exp); throw exp; 41. What is try-with-resources or ARM in Java 7? Java 7 introduced a new form of try known as try-with-resources for Automatic Resource Management (ARM). Here resource is an object that must be closed after the program is finished with it. Example of resources would be an opened file handle or database connection etc. Before the introduction of try-with-resources we had to explicitly close the resources once the try block completes normally or abruptly. try br = new BufferedReader(new FileReader("C:\\test.txt")); System.out.println(br.readLine()); catch (IOException e) e.printstacktrace(); finally try if (br!= null) System.out.println("Closing the file"); br.close(); catch (IOException ex) ex.printstacktrace(); try-with-resources helps in reducing such boiler plate code. Let's see the same example using try-withresources. try(bufferedreader br = new BufferedReader(new FileReader("C:\\test.txt"))) System.out.println(br.readLine()); catch (IOException e) e.printstacktrace(); 42. How to Catch an Exceptions: A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following: 26

27 try //Protected code catch(exceptionname e1) //Catch block A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter. Example: The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception. 27 // File Name : ExcepTest.java import java.io.*; public class ExcepTest public static void main(string args[]) try int a[] = new int[2]; System.out.println("Access element three :" + a[3]); catch(arrayindexoutofboundsexception e) System.out.println("Exception thrown :" + e); System.out.println("Out of the block"); This would produce the following result: Exception thrown :java.lang.arrayindexoutofboundsexception: 3 Out of the block 43. How to use Multiple catch Blocks: A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following: try //Protected code catch(exceptiontype1 e1) //Catch block catch(exceptiontype2 e2) //Catch block catch(exceptiontype3 e3) //Catch block The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. Example: Here is code segment showing how to use multiple try/catch statements.

28 try file = new FileInputStream(fileName); x = (byte) file.read(); catch(ioexception i) i.printstacktrace(); return -1; catch(filenotfoundexception f) //Not valid! f.printstacktrace(); return -1; 44. How to Create an Exception Class public class InsufficientBalanceException extends Exception private final double available; private final double required; /** * Constructor. available available account balance required required account balance */ public InsufficientBalanceException(double available, double required) super("available $"+available+" but required $"+required); this.available = available; this.required = required; /** * Get available account balance available account balance */ public double getavailable() return available; 45. How to declare you own Exception: You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes: All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class. We can define our own Exception class as below: 28 class MyException extends Exception // In Source Packet in file except/ex1/temperatureexception.java class TemperatureException extends Exception // In Source Packet in file except/ex1/toocoldexception.java

29 class TooColdException extends TemperatureException // In Source Packet in file except/ex1/toohotexception.java class TooHotException extends TemperatureException You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods. Example: // File Name InsufficientFundsException.java import java.io.*; public class InsufficientFundsException extends Exception private double amount; public InsufficientFundsException(double amount) this.amount = amount; public double getamount() return amount; To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException. // File Name CheckingAccount.java import java.io.*; public class CheckingAccount private double balance; private int number; public CheckingAccount(int number) this.number = number; public void deposit(double amount) balance += amount; public void withdraw(double amount) throws InsufficientFundsException if(amount <= balance) 29 balance -= amount; else double needs = amount - balance; throw new InsufficientFundsException(needs); public double getbalance() return balance; public int getnumber()

30 return number; The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount. // File Name BankDemo.java public class BankDemo public static void main(string [] args) CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try System.out.println("\nWithdrawing $100..."); c.withdraw(100.00); System.out.println("\nWithdrawing $600..."); c.withdraw(600.00); catch(insufficientfundsexception e) System.out.println("Sorry, but you are short $" + e.getamount()); e.printstacktrace(); Compile all the above three files and run BankDemo, this would produce the following result: Depositing $ Withdrawing $ Withdrawing $ Sorry, but you are short $200.0 InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:25) at BankDemo.main(BankDemo.java:13) 46. Question: Is the following code legal? try finally Answer: Yes, it's legal and very useful A try statement does not have to have a catch block if it has a finally block. If the code in the try statement has multiple exit points and no associated catch clauses, the code in the finally block is executed no matter how the try block is exited. Thus it makes sense to provide a finally block whenever there is code that must always be executed. This include resource recovery code, such as the code to close I/O streams. 30

Software Practice 1 - Error Handling

Software Practice 1 - Error Handling Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5 Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim (42) T.A. Sujin Oh Junseong Lee 1

More information

Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5

Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5 1 Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5 Prof. Hwansoo Han T.A. Jeonghwan Park 41 T.A. Sung-in Hong 42 2 Exception An exception

More information

Here is a hierarchy of classes to deal with Input and Output streams.

Here is a hierarchy of classes to deal with Input and Output streams. PART 15 15. Files and I/O 15.1 Reading and Writing Files A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data

More information

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition Exceptions, try - catch - finally, throws keyword JAVA Standard Edition Java - Exceptions An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring Exceptions BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom

More information

6.Introducing Classes 9. Exceptions

6.Introducing Classes 9. Exceptions 6.Introducing Classes 9. Exceptions Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Learning

More information

BBM 102 Introduction to Programming II Spring 2017

BBM 102 Introduction to Programming II Spring 2017 BBM 102 Introduction to Programming II Spring 2017 Exceptions Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Today What is an exception? What is exception handling? Keywords of exception

More information

Unit 5 - Exception Handling & Multithreaded

Unit 5 - Exception Handling & Multithreaded Exceptions Handling An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/application

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

Exceptions. CSC207 Winter 2017

Exceptions. CSC207 Winter 2017 Exceptions CSC207 Winter 2017 What are exceptions? In Java, an exception is an object. Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment:

More information

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1 Exceptions: An OO Way for Handling Errors Introduction Rarely does a program runs successfully at its very first attempt. It is common to make mistakes while developing as well as typing a program. Such

More information

More on Exception Handling

More on Exception Handling Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

CSC207H: Software Design. Exceptions. CSC207 Winter 2018 Exceptions CSC207 Winter 2018 1 What are exceptions? Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment: not the usual go-tothe-next-step,

More information

Lecture 19 Programming Exceptions CSE11 Fall 2013

Lecture 19 Programming Exceptions CSE11 Fall 2013 Lecture 19 Programming Exceptions CSE11 Fall 2013 When Things go Wrong We've seen a number of run time errors Array Index out of Bounds e.g., Exception in thread "main" java.lang.arrayindexoutofboundsexception:

More information

More on Exception Handling

More on Exception Handling Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

Exception-Handling Overview

Exception-Handling Overview م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the

More information

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

EXCEPTION-HANDLING INTRIVIEW QUESTIONS EXCEPTION-HANDLING INTRIVIEW QUESTIONS Q1.What is an Exception? Ans.An unwanted, unexpected event that disturbs normal flow of the program is called Exception.Example: FileNotFondException. Q2.What is

More information

Exception Handling in Java

Exception Handling in Java Exception Handling in Java The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the runtime errors so that normal flow of the application can be

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 7 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 7 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Essential

More information

EXCEPTION HANDLING. Summer 2018

EXCEPTION HANDLING. Summer 2018 EXCEPTION HANDLING Summer 2018 EXCEPTIONS An exception is an object that represents an error or exceptional event that has occurred. These events are usually errors that occur because the run-time environment

More information

What are Exceptions?

What are Exceptions? Exception Handling What are Exceptions? The traditional approach Exception handing in Java Standard exceptions in Java Multiple catch handlers Catching multiple exceptions finally block Checked vs unchecked

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception

More information

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/

More information

Data Structures. 02 Exception Handling

Data Structures. 02 Exception Handling David Drohan Data Structures 02 Exception Handling JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle River, NJ.

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions

More information

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar Exceptions Introduction to the Java Programming Language Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. CSE 142, Summer 2002 Computer Programming 1. Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»

More information

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1. Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented

More information

Unit III Exception Handling and I/O Exceptions-exception hierarchy-throwing and catching exceptions-built-in exceptions, creating own exceptions, Stack Trace Elements. Input /Output Basics-Streams-Byte

More information

Exceptions - Example. Exceptions - Example

Exceptions - Example. Exceptions - Example - Example //precondition: x >= 0 public void sqrt(double x) double root; if (x < 0.0) //What to do? else //compute the square root of x return root; 1 - Example //precondition: x >= 0 public void sqrt(double

More information

Exceptions Questions https://www.journaldev.com/2167/java-exception-interview-questionsand-answers https://www.baeldung.com/java-exceptions-interview-questions https://javaconceptoftheday.com/java-exception-handling-interviewquestions-and-answers/

More information

Sri Vidya College of Engineering & Technology Question Bank

Sri Vidya College of Engineering & Technology Question Bank 1. What is exception? UNIT III EXCEPTION HANDLING AND I/O Part A Question Bank An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program s instructions.

More information

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed 1 1 COMP200 EXCEPTIONS OOP using Java, based on slides by Shayan Javed Exception Handling 2 3 Errors Syntax Errors Logic Errors Runtime Errors 4 Syntax Errors Arise because language rules weren t followed.

More information

C16b: Exception Handling

C16b: Exception Handling CISC 3120 C16b: Exception Handling Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/28/2018 CUNY Brooklyn College 1 Outline Exceptions Catch and handle exceptions (try/catch)

More information

Errors and Exceptions

Errors and Exceptions 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 reference An exception isn t necessarily your fault trying

More information

UNIT - V. Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O

UNIT - V. Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O UNIT - V Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O 1 INHERITANCE 2 INHERITANCE What is Inheritance? Inheritance is the mechanism which allows a class B to inherit

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Java lecture (10.1) Exception Handling 1 Outline Exception Handling Mechanisms Exception handling fundamentals Exception Types Uncaught exceptions Try and catch Multiple catch

More information

Unit 4. Exception handling mechanism. new look try/catch mechanism in Java Enumeration in Java 5 - usage.

Unit 4. Exception handling mechanism. new look try/catch mechanism in Java Enumeration in Java 5 - usage. Unit 4 Exception handling mechanism. new look try/catch mechanism in Java Enumeration in Java 5 - usage. exceptions An exception is an abnormal condition that arises in a code sequence at run time. an

More information

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions Errors and Exceptions Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception is a problem whose cause is outside

More information

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories Objectives Define exceptions 8 EXCEPTIONS Use try, catch and finally statements Describe exception categories Identify common exceptions Develop programs to handle your own exceptions 271 272 Exceptions

More information

EXCEPTIONS. Java Programming

EXCEPTIONS. Java Programming 8 EXCEPTIONS 271 Objectives Define exceptions Exceptions 8 Use try, catch and finally statements Describe exception categories Identify common exceptions Develop programs to handle your own exceptions

More information

Exception Handling. --After creating exception object,method handover that object to the JVM.

Exception Handling. --After creating exception object,method handover that object to the JVM. Exception Handling 1. Introduction 2. Runtime Stack Mechanism 3. Default Exception Handling in Java 4. Exception Hirarchy 5. Customized Exception Handling By using -catch 6. Control flow in -catch 7. Methods

More information

CSCI 261 Computer Science II

CSCI 261 Computer Science II CSCI 261 Computer Science II Department of Mathematics and Computer Science Lecture 2 Exception Handling New Topic: Exceptions in Java You should now be familiar with: Advanced object-oriented design -

More information

17. Handling Runtime Problems

17. Handling Runtime Problems Handling Runtime Problems 17.1 17. Handling Runtime Problems What are exceptions? Using the try structure Creating your own exceptions Methods that throw exceptions SKILLBUILDERS Handling Runtime Problems

More information

Fundamentals of Object Oriented Programming

Fundamentals of Object Oriented Programming INDIAN INSTITUTE OF TECHNOLOGY ROORKEE Fundamentals of Object Oriented Programming CSN- 103 Dr. R. Balasubramanian Associate Professor Department of Computer Science and Engineering Indian Institute of

More information

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

CS1020 Data Structures and Algorithms I Lecture Note #8. Exceptions Handling exceptional events

CS1020 Data Structures and Algorithms I Lecture Note #8. Exceptions Handling exceptional events CS1020 Data Structures and Algorithms I Lecture Note #8 Exceptions Handling exceptional events Objectives Understand how to use the mechanism of exceptions to handle errors or exceptional events that occur

More information

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166 Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions

More information

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

Exception in thread main java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling. Exceptions 1 Handling exceptions A program will sometimes inadvertently ask the machine to do something which it cannot reasonably do, such as dividing by zero, or attempting to access a non-existent array

More information

For more details on SUN Certifications, visit

For more details on SUN Certifications, visit Exception Handling For more details on SUN Certifications, visit http://sunjavasnips.blogspot.com/ Q: 01 Given: 11. public static void parse(string str) { 12. try { 13. float f = Float.parseFloat(str);

More information

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer

More information

National University. Faculty of Computer Since and Technology Object Oriented Programming

National University. Faculty of Computer Since and Technology Object Oriented Programming National University Faculty of Computer Since and Technology Object Oriented Programming Lec (8) Exceptions in Java Exceptions in Java What is an exception? An exception is an error condition that changes

More information

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes

More information

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling Course Name: Advanced Java Lecture 5 Topics to be covered Exception Handling Exception HandlingHandlingIntroduction An exception is an abnormal condition that arises in a code sequence at run time A Java

More information

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun CS 61B Data Structures and Programming Methodology July 7, 2008 David Sun Announcements You ve started (or finished) project 1, right? Package Visibility public declarations represent specifications what

More information

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology Exceptions Algorithms Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie Exceptions ± Definition

More information

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 8 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 4 is out and due on Tuesday Bugs and Exception handling 2 Bugs... often use the word bug when there

More information

Exception handling in Java. J. Pöial

Exception handling in Java. J. Pöial Exception handling in Java J. Pöial Errors and exceptions Error handling without dedicated tools: return codes, global error states etc. Problem: it is not reasonable (or even possible) to handle each

More information

Exceptions Handling Errors using Exceptions

Exceptions Handling Errors using Exceptions Java Programming in Java Exceptions Handling Errors using Exceptions Exceptions Exception = Exceptional Event Exceptions are: objects, derived from java.lang.throwable. Throwable Objects: Errors (Java

More information

Correctness and Robustness

Correctness and Robustness Correctness and Robustness 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1 Agenda Introduction

More information

Exception Handling CSCI 201 Principles of Software Development

Exception Handling CSCI 201 Principles of Software Development Exception Handling CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Program USC CSCI 201L 2/19 Exception Handling An exception is an indication of a problem

More information

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11 Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday

More information

CS 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction

More information

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws 1 By the end of this lecture, you will be able to differentiate between errors, exceptions,

More information

Unit III Rupali Sherekar 2017

Unit III Rupali Sherekar 2017 Unit III Exceptions An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages that do not support exception

More information

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate

More information

Introductory Programming Exceptions and I/O: sections

Introductory Programming Exceptions and I/O: sections Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate

More information

Chapter 14. Exception Handling and Event Handling ISBN

Chapter 14. Exception Handling and Event Handling ISBN Chapter 14 Exception Handling and Event Handling ISBN 0-321-49362-1 Chapter 14 Topics Introduction to Exception Handling Exception Handling in Ada Exception Handling in C++ Exception Handling in Java Introduction

More information

Java Exception. Wang Yang

Java Exception. Wang Yang Java Exception Wang Yang wyang@njnet.edu.cn Last Chapter Review A Notion of Exception Java Exceptions Exception Handling How to Use Exception User-defined Exceptions Last Chapter Review Last Chapter Review

More information

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017 PIC 20A Exceptions Ernest Ryu UCLA Mathematics Last edited: November 27, 2017 Introductory example Imagine trying to read from a file. import java.io.*; public class Test { public static void main ( String

More information

Chapter 13 Exception Handling

Chapter 13 Exception Handling Chapter 13 Exception Handling 1 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or

More information

Exceptions and Libraries

Exceptions and Libraries Exceptions and Libraries RS 9.3, 6.4 Some slides created by Marty Stepp http://www.cs.washington.edu/143/ Edited by Sarah Heckman 1 Exceptions exception: An object representing an error or unusual condition.

More information

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions Chapter 15 Exception Handling Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference between checked and unchecked exceptions To learn

More information

Chapter 12 Exception Handling

Chapter 12 Exception Handling Chapter 12 Exception Handling 1 Motivations Goal: Robust code. When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can

More information

Introduction Unit 4: Input, output and exceptions

Introduction Unit 4: Input, output and exceptions Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Introduction Unit 4: Input, output and exceptions 1 1.

More information

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 })); A student adds a JUnit test: To Think About @Test public void mogrifytest() { assertequals("mogrify fails", new int[] { 2, 4, 8, 12 }, MyClass.mogrify(new int[] { 1, 2, 4, 6 })); } The test always seems

More information

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616 OBJECT ORIENTED PROGRAMMING Course 6 Loredana STANCIU loredana.stanciu@upt.ro Room B616 Exceptions An event, which occurs during the execution of a program, that disrupts the normal flow of the program's

More information

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski CS 190 - Java Introduction to Java Andy Mroczkowski uamroczk@cs.drexel.edu Department of Computer Science Drexel University February 11, 2008 / Lecture 4 Outline Course Status Course Information & Schedule

More information

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Chapter 8 Exception Handling CS 180 Sunil Prabhakar Department of Computer Science Purdue University Clarifications Auto cast from char to String does not happen. Cast between int and char happens automatically.

More information

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions. Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions...catch...finally throw and throws By the end of this lecture, you will be able to differentiate between errors, exceptions, and

More information

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling CS115 Pi Principles i of fcomputer Science Chapter 17 Exception Handling Prof. Joe X. Zhou Department of Computer Science CS115 ExceptionHandling.1 Objectives in Exception Handling To know what is exception

More information

Full file at Chapter 2 - Inheritance and Exception Handling

Full file at   Chapter 2 - Inheritance and Exception Handling Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a

More information

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);

More information

Date: AIM. Write a Java program to demo simple inheritance PROCEDURE

Date: AIM. Write a Java program to demo simple inheritance PROCEDURE Ex.No 7 Date: AIM INHERITANCE Write a Java program to demo simple inheritance PROCEDURE 1. Create a class stud which includes student name,major,year, rollno. 2. Create a class mark which extends the stud

More information

School of Informatics, University of Edinburgh

School of Informatics, University of Edinburgh CS1Ah Lecture Note 29 Streams and Exceptions We saw back in Lecture Note 9 how to design and implement our own Java classes. An object such as a Student4 object contains related fields such as surname,

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions Overview Problem: Can we detect run-time errors and take corrective action? Try-catch Test for a variety of different program situations

More information

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked exceptions Java try statement Final wishes Java try-resource

More information

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions COMP 213 Advanced Object-oriented Programming Lecture 17 Exceptions Errors Writing programs is not trivial. Most (large) programs that are written contain errors: in some way, the program doesn t do what

More information

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions CS112 Lecture: Exceptions Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions Materials: 1. Online Java documentation to project 2. ExceptionDemo.java to

More information

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions. CS511, HANDOUT 12, 7 February 2007 Exceptions READING: Chapter 4 in [PDJ] rationale for exceptions in general. Pages 56-63 and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines

More information

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions COMP-202 Unit 9: Exceptions Course Evaluations Please do these. -Fast to do -Used to improve course for future. (Winter 2011 had 6 assignments reduced to 4 based on feedback!) 2 Avoiding errors So far,

More information

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved. Chapter 9 Exception Handling Copyright 2016 Pearson Inc. All rights reserved. Last modified 2015-10-02 by C Hoang 9-2 Introduction to Exception Handling Sometimes the best outcome can be when nothing unusual

More information

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others COMP-202 Exceptions Lecture Outline Exceptions Exception Handling The try-catch statement The try-catch-finally statement Exception propagation Checked Exceptions 2 Exceptions An exception is an object

More information

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions A problem?... Exceptions Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions 2 A problem?... A problem?... 3 4 A problem?... A problem?... 5 6 A problem?...

More information

Exceptions. Examples of code which shows the syntax and all that

Exceptions. Examples of code which shows the syntax and all that Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces

More information

Java Errors and Exceptions. Because Murphy s Law never fails

Java Errors and Exceptions. Because Murphy s Law never fails Java Errors and Exceptions Because Murphy s Law never fails 1 Java is the most distressing thing to hit computing since MS-DOS. Alan Kay 2 Corresponding Book Sections Pearson Custom Computer Science: Chapter

More information

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions COMP-202 Unit 9: Exceptions Announcements - Assignment 4: due Monday April 16th - Assignment 4: tutorial - Final exam tutorial next week 2 Exceptions An exception is an object that describes an unusual

More information