Download presentation
Presentation is loading. Please wait.
1
Exception Handling
2
What are errors? What does exception handling allow us to do? Where are exceptions handled? What does exception handling facilitate?
3
What are Exceptions An exception is a java class There are many subclasses of the exception class, each corresponding to a different type of error or abnormal event that we wish to handle Basic concept: –When one of these abnormal events occurs, java will throw an exception –Whenever an exception could possibly be thrown, you must provide a mechanism for catching it in your code
4
Syntax try { } catch ( ) { }
5
Error Handling Where ExceptionType is the class of the thrown exception and refers to an instance of the class Where ExceptionType is the class of the thrown exception and refers to an instance of the class When an exception occurs, an instance of the appropriate class is created and passed to the relevant catch block
6
Error Handling Some possible examples! Catch (IOException e) Catch (FileNotFoundException e) Catch (EOFException e)
7
Catching Exceptions If an exception is thrown inside of a try block, the exception that is returned is forwarded as an argument to the catch block where the exception can be handled
8
Multiple Catch Blocks You can attach multiple catch blocks to a single try block each catching a specific exception Sometimes a method can throw more than one possible exception, or the call block could call 2 different methods that throw 2 different exceptions.
9
Code Example try { //code here } catch (IOException e) { //fix problems } catch (FileNotFoundException e) { //fix problems } catch (Exception e) { //fix problems }
10
Explaining the example Order of catch blocks
11
Example For instance, the constructor New FileInputStream (inFile); Will throw a FileNotFoundException if the file inFile does not exist. Also you will throw an EOFException if you attempt to read beyond the end of the file. You can add multiple catch blocks as: try{….} catch (FileNotFoundException e){ system.out.println (“File” + filename + “does not exist.”); } catch (EOFException e){ System.out.println (“Error: “ + “cannot read beyond end of file”); } catch (IOexception e) { System.out.println(“General I/O exception is thrown”); }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.