Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Java Exception Handling: Understanding Exceptions, try-catch-throw, and Custom Exceptions, Lecture notes of Computer Networks

Java ProgrammingObject-Oriented ProgrammingException HandlingSoftware Development

An overview of java exception handling, explaining the difference between checked and unchecked exceptions, the role of keywords like try, catch, throw, and throws, and the process of creating and handling custom exceptions. It also includes examples of exception handling in java.

What you will learn

  • What is the difference between checked and unchecked exceptions in Java?
  • What is the role of the try, catch, throw, and finally blocks in Java exception handling?
  • What are the different types of exceptions in Java?
  • How can you create and handle user-defined exceptions in Java?
  • How are exceptions handled in Java?

Typology: Lecture notes

2014/2015

Uploaded on 12/28/2015

prianka.bristi
prianka.bristi 🇧🇩

1 document

1 / 43

Toggle sidebar

Related documents


Partial preview of the text

Download Java Exception Handling: Understanding Exceptions, try-catch-throw, and Custom Exceptions and more Lecture notes Computer Networks in PDF only on Docsity! 1 Exception Handling 2 Program Errors  Syntax (compiler) errors  Errors in code construction (grammar, types)  Detected during compilation  Run-time errors  Operations illegal / impossible to execute  Detected during program execution  Treated as exceptions in Java  Logic errors  Operations leading to incorrect program state  May (or may not) lead to run-time errors  Detect by debugging code 5 We can distinguish 3 categories: • checked exceptions — Problems to do with the program's interaction with “the world”. • unchecked exceptions — Problems within the program itself (i.e. violations of the contract, or bugs). • system errors — Problems with the underlying system. These are outside our control. The world is unpredictable, so we would happen in production code, and so These should be removed by testing, and not occur in production code. Unchecked Exceptions System Errors Program System The World Checked Exceptions 6 Exception-Handling Fundamentals  Java exception handling is managed by via five keywords: try, catch, throw, throws, and finally  Program statements to monitor are contained within a try block  If an exception occurs within the try block, it is thrown  Code within catch block catch the exception and handle it  System generated exceptions are automatically thrown by the Java run-time system  To manually throw an exception, use the keyword throw  Any exception that is thrown out of a method must be specified as such by a throws clause 7 Using try and catch  Handling an exception has two benefits,  It allows you to fix the error  It prevents the program from automatically terminating  The catch clause should follow immediately the try block  Once an exception is thrown, program control transfer out of the try block into the catch block  Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism 10 Using try and catch  A try and catch statement form a unit. The scope of the catch clause is restricted to those statements specified by the immediately preceding try statement 11 Uncaught Exceptions  If an exception is not caught by user program, then execution of the program stops and it is caught by the default handler provided by the Java run-time system  Default handler prints a stack trace from the point at which the exception occurred, and terminates the program Ex: class Exc0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } } Output: java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4) Exception in thread "main" 12 Multiple catch Clauses  If more than one can occur, then we use multiple catch clauses  When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed  After one catch statement executes, the others are bypassed 15 Example public class Etest { public static void main(String args[]){ // What we expect to happen System.out.println( x + "/" + y + " = " + x/y ); } try { int x = Integer.parseInt(args[0]); int y = Integer.parseInt(args[1]); catch (NumberFormatException e) { // Things which can go wrong catch (IndexOutOfBoundsException e) { System.out.println( "Usage: Etest <int> <int>" ); } System.out.println( e.getMessage() + " is not a number" ); } // Do this regardless finally { System.out.println( "That's all, folks" ); } } // main } // Etest 16 public class Etest { public static void main(String args[]){ // What we expect to happen System.out.println( x + "/" + y + " = " + x/y ); } try { int x = Integer.parseInt(args[0]); int y = Integer.parseInt(args[1]); catch (NumberFormatException e) { // Things which can go wrong catch (IndexOutOfBoundsException e) { System.out.println( "Usage: Etest <int> <int>" ); } System.out.println( e.getMessage() + " is not a number" ); } // Do this regardless finally { System.out.println( "That's all, folks" ); } } // main } // Etest > java Etest 99 42 99/42 = 2 That's all, folks 17 public class Etest { public static void main(String args[]){ // What we expect to happen System.out.println( x + "/" + y + " = " + x/y ); } try { int x = Integer.parseInt(args[0]); int y = Integer.parseInt(args[1]); catch (NumberFormatException e) { // Things which can go wrong catch (IndexOutOfBoundsException e) { System.out.println( "Usage: Etest <int> <int>" ); } System.out.println( e.getMessage() + " is not a number" ); } // Do this regardless finally { System.out.println( "That's all, folks" ); } } // main } // Etest > java Etest 99 Usage: Etest <int> <int> That's all, folks 20 public class Etest { public static void main(String args[]){ // What we expect to happen System.out.println( x + "/" + y + " = " + x/y ); } try { int x = Integer.parseInt(args[0]); int y = Integer.parseInt(args[1]); catch (NumberFormatException e) { // Things which can go wrong catch (IndexOutOfBoundsException e) { System.out.println( "Usage: Etest <int> <int>" ); } System.out.println( e.getMessage() + " is not a number" ); } // Do this regardless finally { System.out.println( "That's all, folks" ); } } // main } // Etest > java Etest 99 0 That's all, folks java.lang.ArithmeticException: / by zero at Etest.main(Etest.java:8) 21 Using finally for Cleanup Finalizers aren't much good for releasing resources To get guaranteed cleanup of network connections etc. use finally clauses, e.g.: because we don't know when (or even if) they will be called But there's a snag — the call to in.close() may itself throw an exception e.g. if the network goes down at the wrong moment So we actually need a try ... catch block within the finally clause Socket s; InputStream in; try { s = new Socket(...); ... in = s.getInputStream(); ... catch (IOException e) {...} } finally { if (in != null) in.close()); s.close(); } s.close(); finally { try { if (in != null) in.close()); } } catch (IOException e){} 22 With Exception Handling - Example class WithExceptionCatchThrow{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(“Result is “ + r); } catch(ArithmeticException e){ System.out.println(“ B is zero); throw e; } System.out.println(“Program is complete”); } } Program Does Not reach here when exception occurs 25 Exception Hierarchy in Java Throwable Exception RunTimeException Error . . . Unchecked Exceptions System Errors Program System The World Checked Exceptions Error RunTimeException Exception  RunTimeException 26 Representing Exceptions  Exceptions represented as  Objects derived from class Throwable  Code public class Throwable( ) extends Object { Throwable( ) // No error message Throwable( String mesg ) // Error message String getMessage() // Return error mesg void printStackTrace( ) { … } // Record methods … // called & location } 27 Caution  Remember that, exception subclass must come before any of of their superclasses  Because, a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. So, the subclass would never be reached if it come after its superclass  For example, ArithmeticException is a subclass of Exception  Moreover, unreachable code in Java generates error ““ An example nested try statements. class WestTry { public static void mainf{String arge[]) { try { int a = args.length: “® Tf no command line args are present. the following statement will generate @ divide—-by-zero exception. *“ int b= 42 ¥ a: System.out.println( "a = + al: try { -“ nested try block “® Ti one command line arg is used. then an divide—-by-zero exception will be generated by the following code. *- tifta==1) a = avfa-al: “/ division by zero “* Ti two command line args are used then generate an out-of—-bounds exception. *- iffas=2) { int c[] = { 1}: o[42] = 99: “ generate an out-of—-bounds exception + catch(ArrayIndexOutOfBoundsException 6) { System.out.printlin( "Array index cut—of—bounds: + + catch{ArithmeticEsception e) { System.out.println( "Divide by 0: 3 + 8): + } + 2); 30 31 Output  When no parameter is given: Divide by 0: java.lang.ArithmeticException: / by zero  When one parameter is given a = 1 Divide by 0: java.lang.ArithmeticException: / by zero  When two parameters are given a = 2 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException 32 throw  It is possible for your program to to throw an exception explicitly throw TrrowableInstance  Here, TrrowableInstance must be an object of type Throwable or a subclass Throwable  There are two ways to obtain a Throwable objects:  Using a parameter into a catch clause  Creating one with the new operator Example: incorrect program : “f This program contains an error and will not compile. class ThrowsDeno { Lag static vold throvOne() { “oes System.out.printin( "Inside throwlne."); 28 throw nev IllegaldccessException( "demo" ); ed } : 5 public static void main(String args[]) { es throwlne! }: oe } 35 36 Example: corrected version Output: Inside throwOne. Caught java.lang.IllegalAccessException: demo “- Temonstrate finally class= FinallyDemo { “-< Through an e=ception out of the method. Static yoid procaéri { try Syretem.out.printin( "inside procA"): throy new RuntimeEkseception( "“demo"}: + finally { Syestem.out.printin( "“prock'= finally"); + “< Return from within & try block. static vyoid prockei { try S¥retem.cout .prantin( "inside prock"): return: + finally { Syetem. out printin("procB'= finally"); 3 “ Emecute 4a try block normally. static void procter f{ try ft Syetem.out.printinfg “inside proce"): + finally { Syetem.out.printin("proct'= finally"); + + public static void main(String args[]) { try prockt i: +} oceatch (Exception ©&) System.out. printing "“Esception caught"): + procke }: proctlr i: + 37 40 Defining your own exceptions import java.lang.Exception; class InvalidRadiusException extends Exception { private double r; public InvalidRadiusException(double radius){ r = radius; } public void printError(){ System.out.println("Radius [" + r + "] is not valid"); } } 41 Throwing the exception class Circle { double x, y, r; public Circle (double centreX, double centreY, double radius ) throws InvalidRadiusException { if (r <= 0 ) { throw new InvalidRadiusException(radius); } else { x = centreX ; y = centreY; r = radius; } } } 42 Catching the exception class CircleTest { public static void main(String[] args){ try{ Circle c1 = new Circle(10, 10, -1); System.out.println("Circle created"); } catch(InvalidRadiusException e) { e.printError(); } } }