I’m trying to grasp try-catch-finally in Java. I have two questions. These questions might sound silly, please bear in mind that I’m still a beginner.
1) Is it possible/recommended to just wrap a whole method in a try{}block?
See these samples:
The second sample looks cleaner to me. It specifies exactly which lines could throw an exception. But if there functionally any difference between the two? Will the two samples behave differently?
2) Is it possible to make classes and methods for handling exceptions? Say your program has 20 sections that might all throw IOException. Of course, you condense those lines into reusable classes as much as possible, but you still have 20 distinct spots where IOExceptions can be thrown. For whatever reason, the code inside your catch{} blocks is 200 lines long. You could write those 200 lines 20 times over. Instead could you create an ExceptionHandler.java class and put your 200 lines of code in static methods there? Something like:
That seems possible, and it seems like it would be much cleaner.
1) Is it possible/recommended to just wrap a whole method in a try{}block?
See these samples:
Code:
Public void myMethod(){
try{
//200 lines of code
//5 lines of code that might throw an exception
//200 more lines of code
}
catch(someException e){
//do stuff to handle the exception.
}
}
Code:
Public void myMethod(){
//200 lines of code
Try{
//5 lines of code that might throw an exception
}
Catch(someException e){
//do stuff to handle the exception.
}
//200 more lines of code
}
2) Is it possible to make classes and methods for handling exceptions? Say your program has 20 sections that might all throw IOException. Of course, you condense those lines into reusable classes as much as possible, but you still have 20 distinct spots where IOExceptions can be thrown. For whatever reason, the code inside your catch{} blocks is 200 lines long. You could write those 200 lines 20 times over. Instead could you create an ExceptionHandler.java class and put your 200 lines of code in static methods there? Something like:
Code:
Catch(IOException e){ExceptionHandler.ioHandler(e);}
Catch(FileNotFoundException e){ExceptionHandler.fnfHandler(e);}