Exceptions
Throwable is super class for exceptions and errors. there are two types of exceptions in java. Checked Exception and UnChecked Exceptions. All Errors are unchecked exceptions.
Checked exception(Ex: FileNotFoundException, IOExceptions) can be handled at compile time and Unchecked exceptions(Ex: Aithematic Exception) can not be handled at compile time only in run time.
Exceptions can be useful to reprocess your functionality in any interruption happen when jvm executing your instructions step by step.
Try, Catch Block: If any issue occurred in between your code and wanted to handled with proper manuplations then can be placed your sensitive code in try block and can handle all the possible exceptions in catch Block.
public class TryCatchTest1 { public static void main(String[] args) { try{ System.out.println(10/0); }catch(ArithmeticException ae){ ae.printStackTrace(); } } }
Nested Try, Catch Block:
public class NestedTryCatchTest1 {
public static void main(String[] args) { try{ System.out.println(10/0); try{ FileReader fileReader = new FileReader("test.txt"); }catch(FileNotFoundException ae){ ae.printStackTrace(); } }catch(ArithmeticException ae){ ae.printStackTrace(); } } }
Throws: we can handle compile time exceptions can be two ways. in try catch block as shown in above and another one by using throws key word.
class ThrowsTryCatchTest1 {
public static void main(String[] args) throws FileNotFoundException { FileReader fileReader = new FileReader("test.txt"); } }
Throw: throw keyword can be used to trigger any exception on your code based on your conditions.
throw new IllegalAccessError();
finally: finally block can be used when ever you want to execute some sensitive code even if any exceptions occurs.(file closing, network/ DB connections closures..)
public static void main(String[] args) throws IOException { FileOutputStream fos =null; try{ FileReader fileReader = new FileReader("test.txt"); }catch(FileNotFoundException ae){ ae.printStackTrace(); }finally { if(fos!=null) fos.close(); }
Customised Exception: When ever if we want to create new customized exception need to extends Exceptions class.
class CustomizedException extends Exception{ CustomizedException(){ super("CustomizedException message here"); } }
No comments:
Post a Comment