Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Java try-catch block

Java try block

  • Try blocks are used in Java to contain code that might raise an exception. It has to be applied to the method.
    • When encountering an exception within a try block, the subsequent statements will not be executed. Hence, it is recommended to avoid placing non-exceptional code within the try block.
    • In the Java programming language, it is essential to have either a catch block or a finally block following every try block. This ensures proper handling of exceptions and execution of necessary cleanup code.
Table Of Content

  • Java try block
  • Java catch block
  • Problem without exception handling
  • Example of Exception Handling
  • Java Nested try block






Syntax of Java try block

try{    
 //code that could raise an exception
}


Java catch block


  • By stating the type of the exception within the parameter, the Java catch block is used to handle the exception. When dealing with Java Exception Handling, it is essential to declare the parent class exception (Exception) or the specific exception type generated as the declared exception. Declaring the generated type of exception is, however, the best course of action.
  • Only after the try block should the catch block be used. With a single try block, you can combine multiple catch blocks.

Syntax of Java catch block

catch{
   // statement(s) that handle an exception
}






Problem without exception handling


public class Main {	
    public static void main(String args[]){  		 
        int num=20/0; //it will arise  exception  
        System.out.println("Hello World");  
   } 
}

Output:

java.lang.ArithmeticException: / by zero
This Code is unaffected to exception handling 

Exception is arise when we try to divide by zero so rest of code(Hello World) not printed to handle this situation we use exception handling


Example of Exception Handling


package DockerTpoint;
public class Main {	
    public static void main(String args[]){  		 
	  try{  
	      int Num=10/0;  //code inside try block may raise exception
	      System.out.println(Num);
	   }
	  catch(ArithmeticException e){
		  e.printStackTrace();
	  }   // code below catch block will execute normally
      System.out.println("This Code is unaffected to exception handling");  
   } 
}



Output:

 java.lang.ArithmeticException: / by zero
	at HELLO/DockerTpoint.Main.main(Main.java:5)
This Code is unaffected to exception handling 

Exception is arise and handled by catch block and rest of code(This Code is unaffected to exception handling) get printed this is reason why we use exception handling




Example of Exception Handling and rest of code


package DockerTpoint;
public class Main {	
    public static void main(String args[]){  		 
	  try{  
	      int Num=10/0;  //code inside try block may raise exception
	      System.out.println(Num);
	      System.out.println("Code Inside Try Block");
	   }
	  catch(ArithmeticException e){
		  e.printStackTrace();
	  }   // code below catch block will execute normally
      System.out.println("This Code after catch block");  
   } 
}



Output:

 java.lang.ArithmeticException: / by zero
	at HELLO/DockerTpoint.Main.main(Main.java:6)
This Code after catch block 

Exception is arise and handled by catch block but code inside try block is not get printed but rest of code(This Code after catch block) get printed



Example of Exception Handling with Custom Message


package DockerTpoint;
public class Main {	
    public static void main(String args[]){  		 
	  try{  
	      int Num=10/0;  //code inside try block may raise exception
	      System.out.println(Num);
	      System.out.println("Code Inside Try Block");
	   }
	  catch(ArithmeticException e){
		  System.out.println("unable to divide by zero");  
	  }
      System.out.println("This Code after catch block");  
   } 
}



Output:

unable to divide by zero
This Code after catch block 

Exception is arise and handled by catch block but catch block print custom message



Example of Exception Handling when resolvd the exception in catch block


package DockerTpoint;
public class Main {	
    public static void main(String args[]){ 
	   int Num1=10;  
	   int Num2=0;
	  try{  
	      System.out.println(Num1/Num1/Num2);
	      System.out.println("Code Inside Try Block");
	   }
	  catch(ArithmeticException e){
		  Num2=5;
		  System.out.println(Num1/Num2);
	  }
      System.out.println("This Code after catch block");  
   } 
}



Output:

 2
This Code after catch block 

Exception is arise and handled but resolvd the exception in catch block



Java Nested try block


Java allows the use of try blocks inside of other try blocks. The term "nested try block" describes it. The context of the exception is pushed onto the stack with each statement we enter in a try block.

For example in the case, the outer try block can handle the ArrayIndexOutOfBoundsException while the inner try block can handle the ArithemeticException.


There are times when a block may contain a portion that causes one error while the entire block itself causes a different error. Such circumstances necessitate nesting of exception handlers.



Example of Nested try block


public class Main {	
    public static void main(String args[]){    	 
	  try{    
		    try{   //inner try block 1 
		     System.out.println("inner try block");    
		     int Num1 =10/0;    
		    }  
		    catch(ArithmeticException e){  //inner catch block 1 
		      System.out.println(e);  
		    }
		    
		    try{     //inner try block 2
			     int arr[]=new int[10]; 
			     arr[15]=15;    
		     }   
		    catch(ArrayIndexOutOfBoundsException e){  //inner catch block 2 
		       System.out.println(e);  
		    }        
	  }   	  
	  catch(Exception e){  
	    e.printStackTrace(); 
	  }        
	  System.out.println("This Code after outer catch block");  
   } 
}



Output:

inner try block
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 15 out of bounds for length 10
This Code after outer catch block 

Java Multiply Catch Block Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
custom-exception

Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.