Exceptions New Copy
Exceptions New Copy
public Throwable Fills the stack trace of this Throwable object with the current stack
trace, adding to any previous information in the stack trace.
fillInStackTrace()
Exception handling in java uses the following Keywords
• 1.try
• 2. catch
• 3. finally
• 4.throw
• 5.throws
• The try/catch block is used as follows:
• try {
• // block of code to monitor for errors
• // the code you think can raise an exception
•}
• catch (ExceptionType1 exOb) {
• // exception handler for ExceptionType1
• } catch (ExceptionType2 exOb) {
• // exception handler for ExceptionType
• } // optional
• finally { // block of code to be executed after try block ends
• }
Uncaught Exceptions
• class Exc0 {
• public static void main(String[] args) {
• int d = 0; int a = 42 / d;
• }
•}
• java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)
Using try and catch
• Although the default exception handler provided by the Java run time
system is useful for debugging, you will usually want to handle an
exception yourself.
• Doing so provides two benefits. First, it allows you to fix the error.
Second, it prevents the program from automatically terminating.
• class Exc2 {
• public static void main(String[] args) {
• int d, a; try {
• // monitor a block of code.
• d = 0; a = 42 / d;
• System.out.println("This will not be printed.");
• }
• catch (ArithmeticException e) { // catch divide-by-zero error
• System.out.println("Division by zero."); }
• System.out.println("After catch statement."); } }
• OUTPUT:
• This program generates the following output:
• Division by zero. After catch statement.
nested try block
• Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error.
• In such cases, exception handlers have to be nested.
• try {
• statement 1;
• statement 2;
• try {
• statement 1;
• statement 2;
• }
• catch(Exception e) { }
• }
• catch(Exception e) { }
• The following program is an example for Nested try statements.
• class Nestedtry_Example{
• public static void main(String args[]){
• try{
• System.out.println(“division”);
• int a,b; a=0; b =10/a;
• }
• catch(ArithmeticException e) { System.out.println(e); }
• try { int a[]=new int[5]; a[6]=3; }
catch(ArrayIndexOutOfBoundsException e) {
• System.out.println(e); }
• System.out.println(“other statement); }
• catch(Exception e) { System.out.println(“handeled”);}
System.out.println(“normal flow..”); }
• }
Java throw Keyword Definition and
Usage
The throw keyword is used to create a custom error.