찾다
Javajava지도 시간Java의 예외 유형

다음 문서에서는 Java의 예외 유형에 대한 개요를 제공합니다. Java Exception은 프로그램 실행 시 매우 중요한 역할을 합니다. 일반적으로 실행 시 비정상적으로 종료되거나 중단된 프로그램은 예외가 발생합니다. Java Exception은 객체 생성 시 예외가 발생할 때마다 발생하거나 런타임에 오류가 발생하고 예외는 객체 지향 프로그래밍 언어이기 때문에 Java의 객체와 관련됩니다. 따라서 발생한 예외를 포착하고 식별하기 위해 throwable, try 및 catch 블록을 사용하여 예외 및 오류의 계층 구조가 있습니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

Java의 다양한 예외 유형

예외 유형을 담당하는 Java 프로그램의 객체 생성은 다음과 같이 표시되는 계층 구조를 따릅니다.

Java의 예외 유형

프로그래밍 중 Java의 예외는 기본적으로 다음과 같은 두 가지 범주로 나뉩니다.

  • 빌드인 예외: 이는 기존 Java 라이브러리를 사용하여 포착할 수 있는 예외 유형입니다. 확인되지 않은 예외 또는 런타임 예외라고도 합니다.
  • 사용자 정의 예외: 이는 사용자가 만든 일부 사용자 정의 예외를 사용하여 포착할 수 있는 예외 유형이며, 사용자는 이러한 예외를 처리할 수 있어야 합니다. 이러한 예외는 확인 예외 또는 컴파일 시간 예외라고도 합니다.

1. 내장 예외 유형

  • 산술 예외
  • ClassNotFoundException
  • IO예외
  • ArrayIndexOutOfBoundsException
  • FileNotFoundException
  • NullPointerException
  • NoSuchFieldException
  • NoSuchMethodException
  • StringIndexOutOfBoundsException
  • 런타임예외
  • NumberFormatException
  • InterruptedException
아. 산술 예외

이 예외는 산술 계산 시 불일치가 있을 때마다 호출됩니다.

예:

이 프로그램은 산술 예외를 보여줍니다.

코드:

public class Arithmtic_excpn {
public static void main(String[] args) {
{
try {
int first_no = 0;
int scnd_no = 20;
int third_no = 0;
int fourth_no = (first_no-scnd_no)/third_no;
System.out.println ("output after the operation " + fourth_no );
}
catch(ArithmeticException arithmetic_ex) {
System.out.println ("The third number cannot store the value of first number multiplied by second number.");
}
}
}
}

출력:

Java의 예외 유형

ㄴ. ClassNotFoundException

클래스가 제대로 정의되지 않은 경우 ClassNotFoundException이 발생합니다.

예:

이 프로그램은 ClassNotFoundException을 보여줍니다.

코드:

public class Not_Found_Excp {
private static final String mysql_connector = "com.jdbc.mysql-connector";
public static void main(String[] args) throws Exception {
System.out.println("search for the mysql-connector of jdbc for establishing connection.");
Class.forName(mysql_connector);
}
}

출력:

Java의 예외 유형

ㄷ. IO 예외

입력이나 출력 중 어느 하나라도 비정상적으로 종료되어 동작이 실패하게 되면 IO Exception이 발생하게 됩니다.

예:

이 프로그램은 IO 예외를 보여줍니다.

코드:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class IO_Excption_Ex {
public FileInputStream testMethod1(){
File file_a = new File("123.txt");
FileInputStream fileInptstrm = null;
try{
fileInptstrm = new FileInputStream(file_a);
fileInptstrm.read();
}catch (IOException excpn){
excpn.printStackTrace();
}
finally{
try{
if (fileInptstrm != null){
fileInptstrm.close();
}
}catch (IOException excpn){
excpn.printStackTrace();
}
}
return fileInptstrm;
}
public static void main(String[] args){
IO_Excption_Ex inst_1 = new IO_Excption_Ex();
inst_1.testMethod1();
}
}

출력:

Java의 예외 유형

디. ArrayIndexOutOfBoundsException

잘못된 인덱스에 액세스할 때마다 인덱스 범위에 접근할 수 없고 ArrayIndexOutOfBoundsException이 발생합니다.

예:

이 프로그램은 ArrayIndexOutOfBoundsException을 보여줍니다.

코드:

public class Arr_Indx_Out_Of_BOnd {
public static void main(String[] args) {
try{
int ar_0[] = new int[6];
ar_0[8] = 11;
}
catch(ArrayIndexOutOfBoundsException excp){
System.out.println ("Index of the array has crossed the range.");
}
}
}

출력:

Java의 예외 유형

e. FileNotFoundException

경로에 제대로 언급되지 않은 파일이 있거나 제대로 열리지 않은 파일이 있으면 FileNotFoundException이 발생합니다.

예:

이 프로그램은 FileNotFoundException을 보여줍니다.

코드:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class File_Not_Found_Excpt_Exmpl {
private static final String file_nm = "jkl.txt";
public static void main(String[] args) {
BufferedReader rder = null;
try {
rder = new BufferedReader(new FileReader(new File(file_nm)));
String inpt_ln = null;
while ((inpt_ln = rder.readLine()) != null)
System.out.println(inpt_ln);
} catch (IOException excpn) {
System.err.println("catch the IO Exception.");
excpn.printStackTrace();
} finally {
try {
rder.close();
} catch (IOException excpn) {
System.err.println("catch the IO Exception.");
excpn.printStackTrace();
}
}
}
}

출력:

Java의 예외 유형

f. 널 포인터 예외

이러한 유형의 예외는 개체의 구성원이 null 값을 가리키거나 참조할 때마다 발생합니다.

예:

이 프로그램은 Null 포인터 예외를 보여줍니다.

코드:

public class Null_Pointer_Excp {
public static void main(String[] args) {
try {
String art_1 = null;
String art_3= "abc";
System.out.println(art_1.charAt(0));
} catch(NullPointerException excpn) {
System.out.println("This will give a null pointer exception.");
}
}
}

출력:

Java의 예외 유형

지. NoSuchFieldException

이 예외는 필드가 없거나 변수가 존재할 때마다 발생합니다.

예:

이 프로그램은 NoSuchFieldException을 보여줍니다.

코드:

import java.text.DateFormat.Field;
import java.lang.reflect.*;
public class No_suc_field_excpn_Ex {
public static void main(String[] args) {
No_suc_field_excpn_Ex excp = new No_suc_field_excpn_Ex();
Class any_cls = excp.getClass();
System.out.println("value_of_field=");
try {
java.lang.reflect.Field strng_fld = any_cls.getField("One_strng");
System.out.println("field for the public superclass is found: " + strng_fld.toString());
} catch(NoSuchFieldException excpn) {
System.out.println(excpn.toString());
}
}
public No_suc_field_excpn_Ex() {
}
public No_suc_field_excpn_Ex(String One_strng) {
this.val_OneStrng = One_strng;
}
public String val_OneStrng = "Everything appears to be Exception.";
}

출력:

Java의 예외 유형

h. NoSuchMethodException

While trying to access any method in a class and that method is not defined clearly or else is missing will lead to NoSuchMethodException.

Example:

This program demonstrates the NoSuchMethodException.

Code:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class No_Sch_mthd_Ex {
public static String add_rss;
public static String somefiletext;
public static String initial_page_src;
public static void Calculate() throws MalformedURLException {
URL url_a = new URL(add_rss) ;
URLConnection connect_2 = null;
try {
connect_2 = url_a.openConnection();
} catch (IOException excp) {
excp.printStackTrace();
}
BufferedReader buffrr = null;
try {
buffrr = new BufferedReader(
new InputStreamReader(connect_2.getInputStream()));
} catch (IOException excpn) {
excpn.printStackTrace();
}
String filnm_z = "C:\\Users\\adutta\\Documents\\"+"page_src"+"123.txt";
File file_o = new File(filnm_z);
if (!file_o.exists()) {
try {
file_o.createNewFile();
} catch (IOException excpn) {
excpn.printStackTrace();
}
}
FileWriter flwrtr = null;
try {
flwrtr = new FileWriter(filnm_z);
} catch (IOException exc) {
exc.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(flwrtr);
String textreader;
try {
while ((textreader = buffrr.readLine()) != null) {
bw.write(textreader);
}
} catch (IOException excn) {
excn.printStackTrace();
}
}
public static void set_page_src(String page_src){
page_src = initial_page_src;
}
public static void set_url(String addressname){
addressname = add_rss;
}
public static void set_text_file_name(String celeb_filename_p){
celeb_filename_p = celeb_name_i;
}
public static String celeb_name_i = "type_the_text" ;
public static  String url_add_ress = "http//ooo.com";
public static void main(String[] args) {
No_Sch_mthd_Ex.set_page_src(celeb_name_i);
No_Sch_mthd_Ex.set_url(url_add_ress);
try {
No_Sch_mthd_Ex.Calculate();
} catch (IOException excpn) {
excpn.printStackTrace();
}
}
}

Output:

Java의 예외 유형

i. StringIndexOutOfBoundsException

If the index ranging is negative or more than the defined index range in the string class, then it will result into this exception of StringIndexOutOfBoundsException.

Example:

This program demonstrates the StringIndexOutOfBoundsException.

Code:

public class String_Inx_Out_Of_Bound_Ex {
public static void main(String[] args) {
try {
String ant = "ant crawls very slowly.";
char chrct = ant.charAt(50);
System.out.println(chrct);
}
catch(StringIndexOutOfBoundsException excepn) {
System.out.println("String_Out_Of_Bound_Exception occured.");
}
}
}

Output:

Java의 예외 유형

j. RuntimeException

During runtime if any kind of exception arise then these types of exceptions are known as RuntimeException.

Example:

This program demonstrates the RuntimeException.

Code:

public class Runtime_Excp_Ex {
public void Demo_Runtime_Exception () {
throw new Running_Exception();
}
public static void main(String[] args) {
try {
new Running_Exception().Demo_Runtime_Exception();
} catch(Exception excpn) {
System.out.println(excpn.getClass().getName());
}
}
}
class Running_Exception extends RuntimeException {
public Running_Exception() {
super();
}
public void Demo_Runtime_Exception() {
throw new Running_Exception();
}
}

Output:

Java의 예외 유형

k. NumberFormatException

Any exception which cannot get converted into numeric format from the string defined then it will lead to NumberFormatException.

Example:

This program demonstrates the NumberFormatException.

Code:

public class No_Format_Ex {
public static void main(String[] args) {
try {
int value1 = Integer.parseInt ("parasite1") ;
System.out.println(value1);
} catch(NumberFormatException excepn) {
System.out.println("This gives Number Format Exception");
}
}
}

Output:

Java의 예외 유형

l. InterruptedException

If a thread gets disturbed at the time of waiting, sleeping or while performing some processing then it leads to interrupted Exception.

Example:

This program demonstrates the InterruptedException.

Code:

class ChildThread extends Thread {
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException excpn) {
System.err.println("Interuppted_Exception occured.");
excpn.printStackTrace();
}
}
}
public class Interuupted_Excpt_Exmple {
public static void main(String[] args) throws InterruptedException {
ChildThread chldth1 = new ChildThread();
chldth1.start();
chldth1.interrupt();
}
}

Output:

Java의 예외 유형

2. User-Defined Exception

This exception occurs whenever there is some customizable or errors done by user while implementation and execution of program.

Example:

This program demonstrates the user-Defined Exception.

Code:

public class My_Excpn extends Exception {
private static int roll_no[] = {10, 15, 23, 30};
private static String student_Nm[] = {"ani", "viky", "nidhi", "ash"};
private static double marks[] = {20.5, 44.6, 30, 17};
My_Excpn() {    }
My_Excpn(String str)
{
super(str);
}
public static void main(String[] args) {
try  {
System.out.println("roll_no" + "\t" + "student_Nm" +
"\t" + "marks");
for (int i = 0; i 
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500559336989.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Java의 예외 유형" ></p>
<h3 id="Conclusion">Conclusion</h3>
<p>Exceptions in java plays a very pivotal role because it helps in catching and simultaneously throwing of the root cause for an abnormal termination of the program. It often causes and consumes a lot of time for programmers to run and execute programs therefore these kinds of fatal exceptions should not occur frequently at the time of production or even implementation.</p>

위 내용은 Java의 예외 유형의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
플랫폼 독립성은 기업 수준의 Java 응용 프로그램에 어떻게 도움이됩니까?플랫폼 독립성은 기업 수준의 Java 응용 프로그램에 어떻게 도움이됩니까?May 03, 2025 am 12:23 AM

Java는 플랫폼 독립성으로 인해 엔터프라이즈 수준의 응용 프로그램에서 널리 사용됩니다. 1) 플랫폼 독립성은 JVM (Java Virtual Machine)을 통해 구현되므로 JAVA를 지원하는 모든 플랫폼에서 코드가 실행될 수 있습니다. 2) 크로스 플랫폼 배포 및 개발 프로세스를 단순화하여 유연성과 확장 성을 더 많이 제공합니다. 3) 그러나 성능 차이 및 타사 라이브러리 호환성에주의를 기울이고 순수한 Java 코드 사용 및 크로스 플랫폼 테스트와 같은 모범 사례를 채택해야합니다.

Java는 플랫폼 독립성을 고려하여 IoT (Internet of Things) 장치의 개발에서 어떤 역할을합니까?Java는 플랫폼 독립성을 고려하여 IoT (Internet of Things) 장치의 개발에서 어떤 역할을합니까?May 03, 2025 am 12:22 AM

javaplaysaSignificantroleiniotduetoitsplatformincentence.1) itallowscodetobewrittenonceandevices.2) java'secosystemprovidesusefullibrariesforiot.3) itssecurityfeaturesenhanceiotiotsystemsafety.hormormory.hormory.hustupletety.houghmormory

Java에서 플랫폼 별 문제를 발견 한 시나리오와 해결 방법을 설명하십시오.Java에서 플랫폼 별 문제를 발견 한 시나리오와 해결 방법을 설명하십시오.May 03, 2025 am 12:21 AM

thejava.nio.filepackage.1) withsystem.getProperty ( "user.dir") andtherelativeatthereplattHefilePsiple.2) thepathtopilebtoafne 컨버터링 주제

개발자를위한 Java의 플랫폼 독립성의 이점은 무엇입니까?개발자를위한 Java의 플랫폼 독립성의 이점은 무엇입니까?May 03, 2025 am 12:15 AM

Java'SplatformIndenceSnictIficantIficantBecauseItAllowsDeveloperstowRiteCodeOnceAntOnitonAnyplatformwithajvm.이 "WriteOnce, Runanywhere"(WORA) 접근자 : 1) 교차 플랫폼 컴퓨팅 성, DeploymentAcrossDifferentoSwithoutissswithoutissuesswithoutissuesswithoutswithoutisssues를 활성화합니다

다른 서버에서 실행 해야하는 웹 애플리케이션에 Java를 사용하는 장점은 무엇입니까?다른 서버에서 실행 해야하는 웹 애플리케이션에 Java를 사용하는 장점은 무엇입니까?May 03, 2025 am 12:13 AM

Java는 크로스 서버 웹 응용 프로그램을 개발하는 데 적합합니다. 1) Java의 "Write Once, Run Everywhere"철학은 JVM을 지원하는 모든 플랫폼에서 코드를 실행합니다. 2) Java는 Spring 및 Hibernate와 같은 도구를 포함하여 개발 프로세스를 단순화하는 풍부한 생태계를 가지고 있습니다. 3) Java는 성능 및 보안에서 훌륭하게 성능을 발휘하여 효율적인 메모리 관리 및 강력한 보안 보증을 제공합니다.

JVM은 Java의 'Write Once, Run Aloneeringly'(Wora) 기능에 어떻게 기여합니까?JVM은 Java의 'Write Once, Run Aloneeringly'(Wora) 기능에 어떻게 기여합니까?May 02, 2025 am 12:25 AM

JVM은 바이트 코드 해석, 플랫폼 독립 API 및 동적 클래스 로딩을 통해 Java의 Wora 기능을 구현합니다. 1. 바이트 코드는 크로스 플랫폼 작동을 보장하기 위해 기계 코드로 해석됩니다. 2. 표준 API 추상 운영 체제 차이; 3. 클래스는 런타임에 동적으로로드되어 일관성을 보장합니다.

최신 버전의 Java는 플랫폼 별 문제를 어떻게 해결합니까?최신 버전의 Java는 플랫폼 별 문제를 어떻게 해결합니까?May 02, 2025 am 12:18 AM

JAVA의 최신 버전은 JVM 최적화, 표준 라이브러리 개선 및 타사 라이브러리 지원을 통해 플랫폼 별 문제를 효과적으로 해결합니다. 1) Java11의 ZGC와 같은 JVM 최적화는 가비지 수집 성능을 향상시킵니다. 2) Java9의 모듈 시스템과 같은 표준 라이브러리 개선은 플랫폼 관련 문제를 줄입니다. 3) 타사 라이브러리는 OpenCV와 같은 플랫폼 최적화 버전을 제공합니다.

JVM이 수행 한 바이트 코드 검증 프로세스를 설명하십시오.JVM이 수행 한 바이트 코드 검증 프로세스를 설명하십시오.May 02, 2025 am 12:18 AM

JVM의 바이트 코드 검증 프로세스에는 네 가지 주요 단계가 포함됩니다. 1) 클래스 파일 형식이 사양을 준수하는지 확인, 2) 바이트 코드 지침의 유효성과 정확성을 확인하고 3) 유형 안전을 보장하기 위해 데이터 흐름 분석을 수행하고 4) 검증의 철저한 성능 균형을 유지합니다. 이러한 단계를 통해 JVM은 안전하고 올바른 바이트 코드 만 실행되도록하여 프로그램의 무결성과 보안을 보호합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기