Daha önceki Java versiyonlarında, bir try blogundan veya bir metottan birden fazla farklı exception atıldığında, her bir exceptionı ayrı catch bloğunda yakalamamız gerekiyordu.
public void throwTestMethod()
throws IllegalArgumentException, FileNotFoundException, NullPointerException
{
// ...
}
public void throwTest() {
try {
throwTestMethod();
} catch (IllegalArgumentException e) {
// Do special process for IllegalArgumentException
} catch (FileNotFoundException e) {
// Do special process for FileNotFoundException
} catch (NullPointerException e) {
// Do special process for NullPointerException
}
}
Aynı catch bloğunu kullanmanın yolu vardı;
public void throwTest() {
try {
throwTestMethod();
} catch (Exception e) {
// Do special process for all Exceptions
}
}
Ancak, burada gördüğünüz üzere tüm exceptionları aynı blokta kullanmamız gerekiyordu. Örneğin, 3 exception atılan bir metod için sadece 2 exceptiona özel bir blok oluşturamıyorduk (aynı interface’i kullanmak gibi dolambaçlı yöntemler var tabii ki).
Java 7 ile birlikte exceptionları catch bloklarında gruplayabilme özelliği gelmiş oldu. Artık,
public void throwTest() {
try {
throwTestMethod();
} catch (IllegalArgumentException e) {
// Do special process for IllegalArgumentException
} catch (FileNotFoundException | NullPointerException e) {
// Do special process for FileNotFoundException and NullPointerException
}
}
şeklinde bir kullanım gerçekleştirebiliyoruz. Kod yeniden kullanılabilirliği için gayet faydalı bir geliştirme olmuş.